Java I/O流典型使用案例

管道流(多线程程序)

/*
* 创建数据输出线程
* */
class ThreadOut extends Thread{
    private PipedInputStream in;
    private PipedOutputStream out;
    public ThreadOut(PipedInputStream in,PipedOutputStream out){
        this.in = in;
        this.out = out;
    }
    public void run(){
        byte[] bytes = {1,2,3};
        try {
            out.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/*
* 创建数据输入线程
* */
class ThreadIn extends Thread{
    private PipedInputStream in;
    private PipedOutputStream out;
    public ThreadIn(PipedInputStream in,PipedOutputStream out){
        this.in = in;
        this.out = out;
    }
    public void run(){
        try {
            while(in.available()>0){
                int b = in.read();
                System.out.print((byte)b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        /*
        * 连接管道输入输出流
        * */
        in.connect(out);
        new ThreadOut(in,out).start();
        new ThreadIn(in,out).start();
        /*
        * Output:
        * 123
        * */

 

顺序流(合并流)

/*
* 创建实现Enumeration接口的类
* 该类产生多个InputStream流
* SequenceInputStream的构造函数可以接受实现Enumeration的类为参数
* */
class FileList implements Enumeration{
    private String MyFilesList[];
    private int current = 0;
    public FileList(String MyFilesList[]){
        this.MyFilesList = MyFilesList;
    }
    @Override
    public boolean hasMoreElements() {
        if(MyFilesList ==null)
            return false;
        if(current<MyFilesList.length)
            return true;
            else
            return false;

    }
    
    @Override
    public Object nextElement() {
        FileInputStream in = null;
        if(!hasMoreElements())
            return null;
        try {
            in = new FileInputStream(MyFilesList[current]);
            ++current;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return in;
    }
}
        String [] filestr = {"123.txt","456.txt"};
        FileList fileList = new FileList(filestr);
        SequenceInputStream in =new SequenceInputStream(fileList);
        int len = -1;
        byte [] bytes = new byte[1024];
        while(in.read(bytes)!=-1){
            System.out.println(new String(bytes));
        }
        /*
        * Output:
        * Frist file 
        * Second file 
        * */

 

缓冲流(以字符流举例)

/*
* 利用缓冲流读取整行数据。
* */
        BufferedReader in = new BufferedReader(new FileReader("456.txt"));
        StringBuffer str = new StringBuffer();
        String s3=null;
        while((s3 = in.readLine())!=null){
            str.append(s3);
        }
        System.out.println(str);
        /*
        * Output:
        * Second file
        * */

 

字节数组流

        byte[] bytes = {1,2,3};
        /*
        * 将数据存储到字节数组流中的字节数组中
        * 此时字节数组流可看做是一个字节数组来使用
        * */
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(bytes);

        /*
        * 通过字节数组输出流获取字节数组到输入流中写出
        * */
        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        while (in.available()>0) {
            byte b = (byte) in.read();
            System.out.print(b);
        }
        /*
        * Output:
        * 123
        * */



        /*
        * StringReader、StringWriter和数组流有相同的使用方法
        * */
        String s1 = "I love you";
        String s2 = null;
        StringReader strin = new StringReader(s1);
        StringWriter strout = new StringWriter();
        strout.write(s1);
        strout.append(s1);
        s2 = strout.toString();
          System.out.println(s2);
        /*
        *Output:
        * I love youI love you
        * */

 

基本类型流

/*
* 基本类型流
* 基本类型输入输出流要搭配起来使用才有意义
* 在读写中要知道相应的顺序才能得到正确的结果
* */
    DataOutputStream out = new DataOutputStream(new FileOutputStream("456.txt"));
    DataInputStream in = new DataInputStream(new FileInputStream("456.txt"));
    byte b = 1;
    int i = 2;
    double d = 3.05;
    char c = 'a';
    float f = 4.05f;
    String s = "abcdefg";

    out.writeByte(b);
    out.writeUTF(s);
    out.writeChar(c);
    out.writeDouble(d);
    out.writeFloat(f);
    out.writeInt(i);

    System.out.println(in.readByte());
    System.out.println(in.readUTF());
    System.out.println(in.readChar());
    System.out.println(in.readDouble());
    System.out.println(in.readFloat());
    System.out.println(in.readInt());
/*
* Output:
* 1
*abcdefg
*a
*3.05
*4.05
*2
* */

 

打印流

/*
* PrintWriter实现了PrintStream所有的方法
* PrintWriter可以接受一个Outputstream对象作为一个参数
* PrintWriter可以直接对文件进行写入操作
* PrintWriter内置了缓冲,可以使用flush()清空缓冲,也可以使构造器的第二个参数为true实现自动刷新
* System.out是PrintStream。
* */
        PrintStream out1 = System.out;
        out1.printf("输出一串数字%d\n",123456);

        PrintWriter out2 = new PrintWriter(System.out,true);
        out2.printf("输出一串数字%d",456789);
        /*
        * Output:
        * 输出一串数字123456
        * 输出一串数字456789
        * */

        PrintWriter out3 = new PrintWriter("123.txt");
        out3.printf("%s直接对文件进行操作!","PrintWriter可以");
        out3.flush();

 

读写随机访问文件流

import java.io.*;
public class TestIO {
    static void show() throws IOException {
        /*
         * RandomAccessFile类
         * 它不属于InputStream和OutputStream层次体系
         * 其本身跟基本类型流实现了通样的接口所以拥有同样的方法和一些特性
         * seek()方法可接受一个int参数可以访问到文件中相应的字节位置
         * 模式可以为"r","rw"但是不能为"w"只写,因为有写必定有读。
         * */
        RandomAccessFile rf = new RandomAccessFile("456.txt", "r");
        for(int i = 0; i < 7; i++)
            System.out.println(
                    "序列 " + i + ": " + rf.readDouble());
        System.out.println(rf.readUTF());
        rf.close();
    }
    public static void main(String[] args)throws IOException {
        RandomAccessFile rf = new RandomAccessFile("456.txt", "rw");
        for(int i = 0; i < 7; i++)
            rf.writeDouble(i*1.414);
        rf.writeUTF("文件浏览结束");
        rf.close();
        show();
        rf = new RandomAccessFile("456.txt", "rw");
        rf.seek(5*8);
        rf.writeDouble(47.0001);
        rf.close();
        show();
        /*
        * Output:
序列 0: 0.0
序列 1: 1.414
序列 2: 2.828
序列 3: 4.242
序列 4: 5.656
序列 5: 7.069999999999999
序列 6: 8.484
文件浏览结束
序列 0: 0.0
序列 1: 1.414
序列 2: 2.828
序列 3: 4.242
序列 4: 5.656
序列 5: 47.0001
序列 6: 8.484
文件浏览结束
        * */
    }
}

 

posted @ 2018-12-14 19:00  问月晚安  阅读(146)  评论(1编辑  收藏  举报