Xiaobai learns Java: I / O flow

Xiaobai learns Java: I / O flow

Basic classification

Development history

File character stream

Basic structure of output

In practical applications, the exception handling methods need to follow the following structure. In order to save space, this article will use the upward throwing method to handle exceptions.

    //将流对象放在try之外声明,并附为null,保证编译,可以调用close
    FileWriter writer = null;
    try {
        //将流对象放在里面初始化
        writer = new FileWriter("D:\\b.txt");
        writer.write("abc");
        
        //防止关流失败,没有自动冲刷,导致数据丢失
        writer.flush();
        
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //判断writer对象是否成功初始化
        if(writer!=null) {
            //关流,无论成功与否
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //无论关流成功与否,都是有意义的:标为垃圾对象,强制回收
                
                writer = null;
            }
        }
    }

Exception handling in stream

New method of exception handling

JDK1. 7. A new method of exception handling for convection is proposed. Any object of autoclosable type can be used in the try with resources syntax to realize automatic shutdown.

The declaration procedure of the object requiring processing must be in the () following the try, outside the try code block.

try(FileWriter writer = new FileWriter("D:\\c.txt")){
    writer.write("abc");
}catch (IOException e){
    e.printStackTrace();
}

Basic structure of read

The correct way to handle exceptions has been described in the input structure. There will be no complicated exception handling and irresponsible operations thrown directly upward.

    public static void main(String[] args) throws IOException {
        FileReader reader = new FileReader("D:\\b.txt");
        //定义一个变量记录每次读取的字符
        int m;
        //读取到末尾为-1
        while((m = reader.read())!=-1){
           System.out.print(m);
        }
        
        reader.close();
    }

Of course, it's troublesome to read one character at a time. We can improve it:

    //定义数组作为缓冲区
    char[] cs = new char[5];
    //定义变量记录读取字符的个数
    int len;
    while ((len = reader.read(cs)) != -1) {
        System.out.println(new String(cs,len));
    }
    reader.close();

Application input and output

A small case of using file character input and output:

public static void copyFile(FileReader reader,FileWriter writer) throws IOException {
    //利用字符数组作为缓冲区
    char[] cs = new char[5];
    //定义变量记录读取到的字符个数
    int m;
    while((m = reader.read(cs))!=-1){
        //将读取到的内容写入新的文件中
        writer.write(cs,m);

    }
    reader.close();
    writer.close();
}

File byte stream

    public static void main(String[] args) throws Exception {
        FileOutputStream out = new FileOutputStream("D:\\b.txt");
        //写入数据
        //字节输出流没有缓冲区
        out.write("天乔巴夏".getBytes());
        //关流是为了释放文件
        out.close();
    }
    public static void main(String[] args) throws Exception{
        FileInputStream in = new FileInputStream("E:\\1myblog\\Node.png");

       //1.读取字节
       int i = in.read();
       int i;
       while((i=in.read())!=-1)
           System.out.println(i);
       //2.定义字节数组作为缓冲区
       byte[] bs = new byte[10];
       //定义变量记录每次实际读取的字节个数
       int len;
       while((len = in.read(bs))!=-1){
           System.out.println(new String(bs,len));
       }
       in.close();

    }

Buffer stream

Character buffer stream

    public static void main(String[] args) throws IOException {
        //真正读取文件的流是FileReader,它本身并没有缓冲区
        FileReader reader = new FileReader("D:\\b.txt");
        BufferedReader br = new BufferedReader(reader);
        //读取一行
        //String str = br.readLine();
        //System.out.println(str);

        //定义一个变量来记录读取的每一行的数据(回车)
        String str;
        //读取到末尾返回null
        while((str = br.readLine())!=null){
            System.out.println(str);
        }
        //关外层流即可
        br.close();
    }
    public static void main(String[] args) throws Exception {
        //真正向文件中写数据的流是FileWriter,本身具有缓冲区
        //BufferedWriter 提供了更大的缓冲区
        BufferedWriter writer = new BufferedWriter(new FileWriter("E:\\b.txt"));
        writer.write("天乔");
        //换行: Windows中换行是 \r\n   linux中只有\n
        //提供newLine() 统一换行
        writer.newLine();
        writer.write("巴夏");
        writer.close();
    }

Decoration design mode

Buffer flow is based on decoration design pattern, that is, using similar objects to build this class of objects, and changing or enhancing functions in this class.

For example, BufferedReader itself is a reader object. It receives a reader object and constructs itself. It provides buffers and other new methods to improve the speed of input and output by reducing the number of disk reads and writes.

In addition, byte streams also have buffer streams, bufferedinputstream and bufferedoutputstream respectively.

Transform stream (adapter)

The conversion between character stream and byte stream can be realized by using conversion stream.

    public static void main(String[] args) throws Exception {
        //在构建转换流时需要传入一个OutputStream  字节流
        OutputStreamWriter ow = 
                new OutputStreamWriter(
                        new FileOutputStream("D:\\b.txt"),"utf-8");
        //给定字符--> OutputStreamWriter转化为字节-->以字节流形式传入文件FileOutputStream
        //如果没有指定编码,默认使用当前工程的编码
        ow.write("天乔巴夏");
        ow.close();
    }

The final contact with the file is the byte stream, which means that the incoming characters are converted into bytes.

    public static void main(String[] args) throws IOException {
        //以字节形式FileInputStream读取,经过转换InputStreamReader -->字符
        //如果没有指定编码。使用的是默认的工程的编码
        InputStreamReader ir = 
                new InputStreamReader(
                        new FileInputStream("D:\\b.txt"));
        char[] cs = new char[5];
        int len;
        while((len=ir.read(cs))!=-1){
            System.out.println(new String(cs,len));
        }
        ir.close();
    }

The initial contact with the file is the byte stream, which means that the read bytes are converted into characters.

adapter design pattern

Based on the adapter design pattern, the buffer flow converts the interface of one class to the interface of another user's desired class, so that classes that cannot work together due to interface incompatibility can work together.

Take outputstreamwriter as an example. When constructing the conversion stream, a byte stream needs to be passed in, and the written data is initially given in the form of characters, that is, the conversion stream realizes the conversion from characters to bytes, so that two different classes work together.

Standard flow / system flow

Standard flow classification

You can directly use system Out and system Err, but reading system It must be encapsulated before in. For example, we often use the read input before: scanner SC = new scanner (system. In); In fact, it encapsulates the system In object.

    /**
     * 从控制台获取一行数据
     * @throws IOException  readLine 可能会抛出异常
     */
    public static void getLine() throws IOException {
        //获取一行字符数据 -- BufferedReader
        //从控制台获取数据 -- system.in
        //System是字节流,BufferedReader在构建的时候需要传入字符流
        //将字节流转换为字符流
        BufferedReader br =
                new BufferedReader(
                        new InputStreamReader(system.in));
        //接收标准输入并转换为大写
        String str = br.readLine().toUpperCase();
        //发送到标准输出
        System.out.println(str);
    }

By converting the stream, the system The standard input byte stream read in is converted into character stream and sent to standard output for printing and display.

Print stream

    public static void main(String[] args) throws IOException {
        //创建PrintStream对象
        PrintStream p = new PrintStream("D:\\b.txt");
        p.write("abc".getBytes());
        p.write("def".getBytes());
        p.println("abc");
        p.println("def");
        //如果打印对象,默认调用对象身上的toString方法
        p.println(new Object());
        p.close();
    }
    //将System.out转换为PrintStream
    public static void main(String[] args) {
        //第二个参数autoFlash设置为true,否则看不到结果
        PrintWriter p = new PrintWriter(System.out,true);
        p.println("hello,world!");
    }

Merge flow

Taking the first construction method as an example, as we said earlier, enumeration can be created through the elements method of the vector container.

    public static void main(String[] args) throws IOException {
        FileInputStream in1 = new FileInputStream("D:\\1.txt");
        FileInputStream in2 = new FileInputStream("D:\\a.txt");
        FileInputStream in3 = new FileInputStream("D:\\b.txt");
        FileInputStream in4 = new FileInputStream("D:\\m.txt");

        FileOutputStream out = new FileOutputStream("D:\\union.txt");
        //准备一个Vector存储输入流
        Vector<InputStream> v = new Vector<>();
        v.add(in1);
        v.add(in2);
        v.add(in3);
        v.add(in4);

        //利用Vector产生Enumeration对象
        Enumeration<InputStream> e = v.elements();
        //利用迭代器构建合并流
        SequenceInputStream s = new SequenceInputStream(e);

        //读取
        byte[] bs = new byte[10];
        int len;
        while((len = s.read(bs))!=-1){
            out.write(bs,len);
        }
        out.close();
        s.close();
    }

Serialize / deserialize stream

serialized objects

Create a person class.

//必须实现Serializable接口
class Person implements Serializable {
    //序列化ID serialVersionUID
    private static final long serialVersionUID = 6402392549803169300L;
    private String name;
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Create a serialized stream, convert the object to bytes, and write "D: \ 1. Data".

public class ObjectOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        Person p = new Person();
        p.setAge(18);
        p.setName("Niu");
        //创建序列化流
        //真正将数据写出的流是FileOutputStream
        //ObjectOutputStream将对象转化为字节
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\1.data"));
        out.writeObject(p);
        out.close();
    }
}

Create a deserialization stream to convert the bytes read from "D: \ 1. Data" into objects.

    public static void main(String[] args) throws IOException,ClassNotFoundException {
        //创建反序列化流
        //真正读取文件的是FileInputStream
        //ObjectInputStream将读取的字节转化为对象
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\1.data"));
        //读取数据必须进行数据类型的强制转换
        Person p = (Person)in.readObject();
        in.close();
        System.out.println(p.getName());//Niu
        System.out.println(p.getAge());//18

    }

It should be noted that:

About version number:

Write at the end: if there are narrative errors in this article, we also hope to criticize and correct in the comment area and make common progress.

References: Java programming ideas, Java language programming, Dahua design pattern

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>