The four major streams in Java: [buffer stream] [conversion stream] [object stream] [print stream]

Article directory

  • buffered stream
    • 1 Overview
    • 2. Efficiency test
      • byte buffer stream
      • character buffer stream
  • Conversion flow
    • Character encodings and character sets
      • Character Encoding
      • character set
    • InputStreamReader class
      • Specify encoding to read
    • OutputStreamWriter class
      • Specify encoding to write
  • object stream
    • ObjectOutputStream class
      • Serialization operation
    • ObjectInputStream class
  • print stream


This article mainly introduces the basic concepts and basic usage of the three major streams in Java

Buffered stream

1. Overview

Buffered streams, also called efficient streams, are enhancements to the four basic FileXxx streams, so they are also four streams, classified according to data type:
1. Byte buffer stream: BufferedInputStream, BufferedOutputStream
2. Character buffer stream: BufferedReader, BufferedWriter
Basic principles of buffered streams:
When creating a stream object, a built-in buffer array of default size is created. Reading and writing through the buffer reduces the number of system IOs, thereby improving the efficiency of reading and writing.

2. Efficiency test

Byte buffer stream

Explore why buffered streams are called efficient streams through code.
Basic flow:

package BoKe.javaadvance;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedDemo {<!-- -->
    public static void main(String[] args) throws FileNotFoundException {<!-- -->
        // Record start time
        long start = System.currentTimeMillis();
        //Create stream object
        try (
                FileInputStream fis = new FileInputStream("C:\A-h Study\utils\\jquery.api.3.2.1.chm");
                FileOutputStream fos = new FileOutputStream("C:\A-h Study\utils\test\\jquery.api.3.2.1.chm")
        ) {<!-- -->
        //Read and write data
            int b;
            while ((b = fis.read()) != -1){<!-- -->
                fos.write(b);
            }
        } catch (IOException e) {<!-- -->
            e.printStackTrace();
        }
        //record end time
        long end = System.currentTimeMillis();
        System.out.println("Normal stream copy time:" + (end - start) + "milliseconds");
    }
}

Buffered stream:

package BoKe.javaadvance;

import java.io.*;

public class BufferedDemo {<!-- -->
    public static void main(String[] args) throws FileNotFoundException {<!-- -->
        // Record start time
        long start = System.currentTimeMillis();
        //Create stream object
        try (
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\test1\java.exe"));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\test1\\a\copy.exe"));
        ) {<!-- -->
            //Read and write data
            int b;
            while ((b = bis.read()) != -1){<!-- -->
                bos.write(b);
            }
        } catch (IOException e) {<!-- -->
            e.printStackTrace();
        }
        //record end time
        long end = System.currentTimeMillis();
        System.out.println("Buffered stream copy time:" + (end - start) + "milliseconds");
    }
}


From the above test, we can see that using buffered streams allows us to read and write files efficiently.

Of course, we can also use arrays to make us read files faster

package BoKe.javaadvance;

import java.io.*;

public class BufferedDemo {<!-- -->
    public static void main(String[] args) throws FileNotFoundException {<!-- -->
// Record start time
        long start = System.currentTimeMillis();
//Create stream object
        try (
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
        ) {<!-- -->
//Read and write data
            int len;
            byte[] bytes = new byte[8 * 1024];
            while ((len = bis.read(bytes)) != -1){<!-- -->
                bos.write(bytes, 0, len);
            }
        } catch (IOException e) {<!-- -->
            e.printStackTrace();
        }
//record end time
        long end = System.currentTimeMillis();
        System.out.println("Buffered stream uses array copy time:" + (end - start) + "milliseconds");
    }
}

Character buffer stream

Points to note:
Character buffer stream has its special methods readLine(), newLine()
Code demo:
readLine() method

public class BufferedReaderDemo {<!-- -->
    public static void main(String[] args) throws IOException {<!-- -->
        //Create stream object
        BufferedReader br = new BufferedReader(new FileReader("in.txt"));
        //Define a string and save the read line of text
        String line = null;
        // Loop reading, return null after reading to the end
        while ((line = br.readLine())!=null) {<!-- -->
            System.out.print(line);
            System.out.println("‐‐‐‐‐‐");
        }
        // Release resources
        br.close();
    }
}

newLine() method

public class BufferedWriterDemo throws IOException {<!-- -->
    public static void main(String[] args) throws IOException {<!-- -->
        //Create stream object
        BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
        // write data
        bw.write("Heaven and Earth Club");
        // write newline
        bw.newLine();
        bw.write("Cheng Jin");
        bw.newLine();
        bw.write("南");
        bw.newLine();
        // Release resources
        bw.close();
    }
}

Conversion stream

Foreword: Character encoding and character set

Character encoding and character set

Character encoding

  • The information stored in the computer is represented by binary numbers, and the numbers, English, punctuation marks, Chinese characters and other characters we see on the screen are the results of binary number conversion. Storing characters into the computer according to certain rules is called encoding. On the contrary, parsing and displaying the binary numbers stored in the computer according to certain rules is called decoding. For example, if it is stored according to A rules and parsed according to A rules, then the correct text f symbol can be displayed. On the contrary, storing according to rules A and parsing according to rules B will lead to garbled characters.

Character set

  • Character set (Charset): also called encoding table. It is a collection of all characters supported by the system, including various national characters, punctuation marks, graphic symbols, numbers, etc.

InputStreamReader class

Conversion stream java.io.InputStreamReader is a subclass of Reader and a bridge from byte stream to character stream. It reads bytes and decodes them into characters using the specified character set. Its character set can be specified by name, or it can accept the platform's default character set.

Specify encoding to read

package BoKe.javaadvance;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReaderDemo2 {<!-- -->
    public static void main(String[] args) throws IOException {<!-- -->
        //Define the file path, the file is gbk encoded
        String FileName = "C:\test1\a.txt";
        //Create stream object, default UTF8 encoding
        InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName));
        //Create a stream object and specify GBK encoding
        InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName), "GBK");
        //Define variables and save characters
        int read;
        // Use the default encoding character stream to read, garbled characters
        while ((read = isr.read()) != -1){<!-- -->
            System.out.print((char) read); // 
        }
        isr.close();
        System.out.println();
        // Use the specified encoding character stream to read and parse normally
        while ((read = isr2.read()) != -1){<!-- -->
            System.out.print((char) read);// Hello everyone
        }
        isr2.close();
    }
}

OutputStreamWriter class

Conversion stream java.io.OutputStreamWriter is a subclass of Writer and a bridge from character stream to byte stream. Encode characters into bytes using the specified character set. Its character set can be specified by name, or it can accept the platform's default character set.

Specify encoding to write

public class OutputDemo {<!-- -->
    public static void main(String[] args) throws IOException {<!-- -->
        //Define file path
        String FileName = "E:\out.txt";
        //Create stream object, default UTF8 encoding
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));
        // write data
        osw.write("Hello"); // Save as 6 bytes
        osw.close();
        //Define file path
        String FileName2 = "E:\out2.txt";
        //Create a stream object and specify GBK encoding
        OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK");
        // write data
        osw2.write("Hello"); // Save as 4 bytes
        osw2.close();
    }
}

Conversion stream understanding diagram:

Object stream

The main function of object stream is serialization

ObjectOutputStream class

java.io.ObjectOutputStream class writes out the original data type of Java objects to files to achieve persistent storage of objects.

Serialization operation

Condition:
1. This class must implement the java.io.Serializable interface. Serializable is a mark interface. Classes that do not implement this interface will not serialize or deserialize any state and will throw NotSerializableException.
2. All properties of this class must be serializable. If there is an attribute that does not need to be serializable, the attribute must be marked as transient and modified using the transient keyword.
Example:
1. Create an Employee class and make it inherit the Serializable interface.

package BoKe.javaadvance;

public class Employee implements java.io.Serializable {<!-- -->
    public String name;
    public String address;
    public transient int age; // transient modified members will not be serialized

    public void addressCheck() {<!-- -->
        System.out.println("Address check : " + name + " ‐‐ " + address);
    }
}

2. Create a test class for testing.

package BoKe.javaadvance;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeDemo {<!-- -->
    public static void main(String[] args) {<!-- -->
        Employee e = new Employee();
        e.name = "zhangsan";
        e.address = "beiqinglu";
        e.age = 20;
        try {<!-- -->
            //Create serialization stream object
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\test1\\employee.txt"));
            // write object
            out.writeObject(e);
            // Release resources
            out.close();

            System.out.println("Serialized data is saved"); // Name and address are serialized, but age is not serialized.
        } catch (IOException i) {<!-- -->
            i.printStackTrace();
        }
    }
}


Through the above running results, we can see that our object has been stored in memory and serialized.

ObjectInputStream class

ObjectInputStream deserializes the stream and restores the original data previously serialized using ObjectOutputStream into objects.
Here we read the object that has just been serialized

package BoKe.javaadvance;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeDemo {<!-- -->
    public static void main(String[] args) {<!-- -->
        Employee e = null;
        try {<!-- -->
            //Create deserialization stream
            FileInputStream fileIn = new FileInputStream("C:\test1\\employee.txt");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            // read an object
            e = (Employee) in.readObject();
            // Release resources
            in.close();
            fileIn.close();
        } catch (IOException i) {<!-- -->
            //Catch other exceptions
            i.printStackTrace();
            return;
        } catch (ClassNotFoundException c) {<!-- -->
            //Catch class not found exception
            System.out.println("Employee class not found");
            c.printStackTrace();
            return;
        }
        // No exception, print output directly
        System.out.println("Name: " + e.name); // zhangsan
        System.out.println("Address: " + e.address); // beiqinglu
        System.out.println("age: " + e.age); // 0
    }
}

Print stream

Usually we print output on the console by calling the print method and println method. Both methods come from the java.io.PrintStream class, which can conveniently print values of various data types. A convenient output method.
Code example:

public class PrintDemo {<!-- -->
public static void main(String[] args) throws IOException {<!-- -->
// Call the system's print stream, and the console directly outputs 97
System.out.println(97);
//Create a print stream and specify the name of the file
PrintStream ps = new PrintStream("C:\test1\\employee.txt");
//Set the system's print flow direction and output to ps.txt
System.setOut(ps);
// Call the system's print stream, output 97 in ps.txt
System.out.println(97);
}
}

The above are the basic methods of using the four major stream objects in Java. Of course, there are definitely more than these streams in Java. Interested friends can learn more about it~