Why an I/0 stream

  1. When our program needs to go fromHard drive, network, or other applicationsWhen reading or writing data, the amount of data transfer may be very large, and ourLimited memory or bandwidthCannot read, obtain, and write large amounts of data at once.
  2. A Stream, on the other hand, enables the gradual transmission of data bit by bit.
  3. Think about how we can download a large file. Downloading software (such as Thunder X) doesn’t take up a lot of memory, but just partition a buffer in memory and download it to your own memory bit by bit (write it to hard disk when the buffer is full).

Stream

  1. Stream is a Java class that is used for input and output operations before Java programs and peripherals.
  2. An external device can be a file on a hard disk, a network device, or another Java program.
  3. Different input/output sources (keyboards, files, network connections, etc.) are abstracted as “streams” in Java. Streams allow Java programs to access different input/output sources in the same way. Stream is the ordered data from the source to the received (sink).
  4. In the picture below, the input and output streams are like pipes that connect the program to the water tank, letting the water trickle through.

I/O traffic classification

  1. Specific classification of I/O flows
    • Divided by direction of flow: divided intoThe input stream.The output stream
    • By the transmission unit of a stream: divided intoByte stream(8 bits),Characters of the flow(16-bit characters)
    • By role of stream: divided intoThe node flow.Processing flow
      • Node flows are directly connectedThe data sourceThe flow can beRead and write data directly to data sources (specific IO devices, such as hard disks, networks, and other programs).
      • Treatment flow overThe constructor receives a node stream, used for node flowsDecorator patternAdd more functionality to handle streamsMust depend on a node flowBecause only the node stream can ultimately send the data stream in and out to the IO device.
  2. Java puts all traditional stream types in the java.io package for input and output functionality.
  3. There are so many classes for streams in this package that it can be confusing for beginners, but keep in mind that Java I/0 has four base classes, and all IO stream implementation classes are subclasses of that.

I/O flow architecture architecture

Node flows – flows that connect directly to data sources

Common node flows

  1. File File flow. Read and write files: FileReader, FileWriter, FileInputStream, and FileOutputStream.
  2. Read and write data from/to an in-memory array: CharArrayReader and CharArrayWriter, ByteArrayInputStream and ByteArrayOutputStream.
  3. Reads and writes StringReader, StringWriter, and StringBufferInputStream from/to an in-memory string.
  4. Pipe Pipe flow. Implement the input and output of pipes (interprocess communication) : PipedReader and PipedWriter, PipedInputStream and PipedOutputStream.

Process streams – Join existing streams

Common processing flows

  1. Buffering Buffering streams: Cache data while reading or writing to reduce I/ OS: BufferedReader and BufferedWriter, BufferedInputStream and BufferedOutputStream.
  2. Filtering: Filters data while it is being read or written: FilterReader and FilterWriter, FilterInputStream and FilterOutputStream.
  3. 29. Converting between Bytes and Characters To convert a byte Stream into a character Stream or reverse (Stream to Reader) according to certain encoding/decoding criteria: InputStreamReader, OutputStreamWriter.
  4. Object Serialization Object flows: ObjectInputStream, ObjectOutputStream.
  5. DataConversion Data stream: Reads and writes according to basic data types (processing data is Java basic types (such as Booleans, bytes, integers, and floating point numbers) : DataInputStream, DataOutputStream.
  6. Counting count flow: Counts the number of rows when data is read. The options are LineNumberReader and LineNumberInputStream.
  7. Peeking Ahead prefetch: uses the caching mechanism to prefetch: PushbackReader and PushbackInputStream. 8.Printing stream: contains convenient Printing methods: PrintWriter, PrintStream.

FileInputStream & FileOutputStream

  1. FileInputStream & FileOutputStream can read/write raw byte streams such as image data from the file system.
  2. The following is an example of copying files using FileInputStream & FileOutputStream
Private static void copyFile1(String SRC, String dest) throws IOException {//1. Create a flow InputStreamin= new FileInputStream(src); OutputStream os = new FileOutputStream(dest); Int data = in.read();while(data ! = -1) { os.write(data); data = in.read(); } //3. Close the stream in.close(); os.close(); Private static void copyFile2(String SRC, String dest) throws IOException {//1. Create a flow InputStreamin= new FileInputStream(src); OutputStream os = new FileOutputStream(dest); Byte [] buffer = new byte[2048]; int len = in.read(buffer);while(len ! = -1) { os.write(buffer, 0, len); len = in.read(buffer); } //3. Close the stream in.close(); os.close(); }Copy the code

DataInputStream & DataOutputStream

  1. DataInputStream and DataOutputStream are processing streams. Instead, the constructor receives an existing input and output stream, allowing programs to easily and quickly manipulate Java’s basic data types from reading.
Private static void Write (String Dest) throws IOException {//1. DataOutputStream OS = new DataOutputStream(new FileOutputStream(dest)); //2. Write data os.writeint (10); os.writeChar('a');
        os.writeChar('b'); OS. WriteDouble (12.83); //3. Close the stream os.close(); } // Read Java basic data types from files in the same order as they were writtenread(String src) throws IOException { //1. Create the DataInputStream objectin= new DataInputStream(new FileInputStream(src)); Int a = in.readint (); char b = in.readChar(); char c = in.readChar(); double d = in.readDouble(); //3. Close the stream in.close(); }Copy the code

BufferedInputStream & BufferedOutputStream

  1. BufferedInputStream & BufferedOutputStream adds some functionality to another input/output stream, the function of a buffer. When BufferedInputStream & BufferedOutputStream is created, an array of internal buffers is created.
// Add buffer function for file byte stream, read and write one byte at a time, Private static void copyFile1(String SRC, String dest) throws IOException {//1. Create a flow InputStreamin= new BufferedInputStream(new FileInputStream(src)); OutputStream os = new BufferedOutputStream(new FileOutputStream(dest)); Int data = in.read();while(data ! = -1) { os.write(data); data = in.read(); } //3. Close the stream in.close(); os.close(); } // Add buffer function for file byte stream, read and write one byte array data at a time, Private static void copyFile2(String SRC, String dest) throws IOException {//1. Create a flow InputStreamin= new BufferedInputStream(new FileInputStream(src)); OutputStream os = new BufferedOutputStream(new FileOutputStream(dest)); Byte [] buffer = new byte[2048]; int len = in.read(buffer);while(len ! = -1) { os.write(buffer, 0, len); len = in.read(buffer); } //3. Close the stream in.close(); os.close(); }Copy the code

PrintStream

  1. PrintStream adds functionality to other output streams, enabling them to easily print various data value representations.
public static void main(String[] args) throws FileNotFoundException {

        PrintStream ps = new PrintStream("test.txt");
        ps.println(5);
        ps.print("Aaaa");
        ps.print(false);
        ps.println("hahah");

        ps.flush();
        ps.close();
    }
Copy the code

ByteArrayInputStream & ByteArrayInputStream

  1. ByteArrayInputStream & ByteArrayInputStream contains an internal buffer (essentially writing data to memory and then reading it) that contains bytes read from the stream. The internal counter tracks the next byte to be supplied by the read method.
public static void main(String[] args) throws IOException { //1. Write data ByteArrayOutputStream OS = new ByteArrayOutputStream(); os.write("hello".getBytes()); os.close(); Byte [] bytes = os.tobytearray (); byte[] bytes = os.tobytearray (); ByteArrayInputStreamin = new ByteArrayInputStream(bytes);

        byte[] data = new byte[1014];
        int len = in.read(data);
        System.out.println(new String(data, 0 ,len));

    }
Copy the code

InputStreamReader & OutputStreamWriter

  1. Java in jdk1.1 provides a convenient class for character processing, character stream, the original byte stream, added character encoding table encoding processing capabilities
  2. Byte stream to character stream conversion stream, the read () and writer () methods will input and output more than one byte at a time to wrap character conversion,
  3. Byte stream + encoding table = InputStreamReader & OutputStreamWriter
Private static void copyFile1(String SRC, String dest) throws IOException {//1. Reader Reader = new InputStreamReader(new FileInputStream(SRC)); Writer writer = new OutputStreamWriter(new FileOutputStream(dest)); Int data = reader.read();while(data ! = -1) { writer.write(data); data = reader.read(); } //3. Close the stream reader.close(); writer.close(); } // Copy one character array at a time private static void copyFile2(String SRC, String dest) throws IOException {//1. Reader Reader = new InputStreamReader(new FileInputStream(SRC)); Writer writer = new OutputStreamWriter(new FileOutputStream(dest)); Char [] buffer = new char[2048]; int len = reader.read(buffer);while(len ! = -1) { writer.write(buffer, 0 , len); len = reader.read(buffer); } //3. Close the stream reader.close(); writer.close(); }Copy the code

FileReader & FileWriter

  1. When only writing characters to files, the JDK provides a subclass of byte conversion stream FileReader & FileWriter to facilitate the IO operation of character files because it is too troublesome to wrap the byte stream each time using conversion stream
Private static void copyFile1(String SRC, String dest) throws IOException {//1. Reader = new FileReader(SRC); Writer writer = new FileWriter(dest); Int data = reader.read();while(data ! = -1) { writer.write(data); data = reader.read(); } //3. Close the stream reader.close(); writer.close(); } // Copy one character array at a time private static void copyFile2(String SRC, String dest) throws IOException {//1. Reader = new FileReader(SRC); Writer writer = new FileWriter(dest); Char [] buffer = new char[2048]; int len = reader.read(buffer);while(len ! = -1) { writer.write(buffer, 0 , len); len = reader.read(buffer); } //3. Close the stream reader.close(); writer.close(); }Copy the code

BufferedReader & BufferedWriter

Private static void copyFile1(String SRC, String dest) throws IOException {//1. Reader = new BufferedReader(new FileReader(SRC)); Writer writer = new BufferedWriter(new FileWriter(dest)); Int data = reader.read();while(data ! = -1) { writer.write(data); data = reader.read(); } //3. Close the stream reader.close(); writer.close(); } // Copy one character array at a time private static void copyFile2(String SRC, String dest) throws IOException {//1. Reader = new BufferedReader(new FileReader(SRC)); Writer writer = new BufferedWriter(new FileWriter(dest)); Char [] buffer = new char[2048]; int len = reader.read(buffer);while(len ! = -1) { writer.write(buffer, 0 , len); len = reader.read(buffer); } //3. Close the stream reader.close(); writer.close(); Private static void copyFile3(String SRC, String dest) throws IOException {//1. BufferedReader = new BufferedReader(new FileReader(SRC)); BufferedWriter writer = new BufferedWriter(new FileWriter(dest)); String data = reader.readline ();while(data ! = null) { writer.write(data); writer.newLine(); data = reader.readLine(); } //3. Close the stream reader.close(); writer.close(); }Copy the code

StringReader & StringWriter

  1. Easily and quickly write a string to or read from memory
public static void main(String[] args) throws IOException, NoSuchFieldException { //1. Writes data to memory and provides a buffer. StringWriter Writer = new StringWriter(); writer.write("hello world"); StringReader = new StringReader(writer.toString()); char[] data = new char[1024]; int len = reader.read(data); System.out.println(new String(data,0,len)); }Copy the code