IO flow - power node notes

@author: posper
@date: 2021/7/8-2021/7/9
@version: v1.0

This document is based on Power node IO flow p720-756 finishing

IO stream

Classification of IO streams

  • Classify according to the direction of the flow (take the memory as the reference):

    • Input stream

      • Going to memory is called input. Or read
    • Output stream

      • Coming out of memory is called output. Or write
  • Classify according to different data reading methods:

    • Byte stream
      • Read data in the way of bytes. Reading 1 byte at a time is equivalent to reading 8 binaries at a time
      • This stream is omnipotent. Any type of file can be read. Including: text file, picture, sound file, video
    • Character stream
      • If data is read in character mode, read one character at a time (different codes, one character may contain multiple characters, such as utf-8)
      • This stream exists to facilitate reading ordinary text files. This stream cannot read pictures, sounds, videos and other files. You can only read plain text files, not even word files.

"Four families" of Java IO streams

  • Leaders of the four families:

    • java.io.Inputstream byte input stream
    • java.io.Outputstream byte output stream
    • java.io.Reader character input stream
    • java.io.Writer character output stream

    Note: in Java, as long as the "class name" ends with stream, it is a byte stream. All characters ending with "Reader/writer" are character streams

  • The leaders of the four families are abstract classes

  • All streams implement Java io. Closable interfaces are closable and have a close() method.

    • Stream is a pipe, which is the channel between memory and hard disk;
    • Be sure to close the stream after it is used up, otherwise it will consume (occupy) a lot of resources.
  • All output streams implement Java io. Flushable interfaces are refreshable and have flush() methods.

    • Form a good habit. After the final output of the output stream, you must remember to refresh with flush().

    • This refresh indicates that the remaining non output data in the channel / pipeline is forcibly output (empty the pipeline!), That is, the function of refresh is to empty the pipeline.

    Note: failure to flush() may result in data loss.

IO streams commonly used in Java

  • java. Streams to master under IO package (16):

    Focus on mastering FileInputStream and FileOutputStream. Other usages are similar. Just check the api document

    • File Exclusive:
      • java.io.FileInputStream (Master)
      • java.io.FileOutputStream (Master)
      • java.io.FileReader
      • java.io.FileWriter
    • Convert stream: (convert byte stream to character stream)
      • java.io.InputStreamReader
      • java.io.OutputStreamWriter
    • Buffer stream exclusive
      • java.io.BufferedReader
      • java.io.BufferedWriter
      • java.io.BufferedInputStream
      • java.io.BufferedOutputStream
    • Data flow exclusive
      • java.io.DataInputStream
      • java.io.DataOutputStream
    • Standard output stream
      • java.io.PrintWriter
      • java.io.PrintStream (Master)
    • Object specific flow
      • java.io.ObjectInputStream (Master)
      • java.io.ObjectOutputStream (Master)

    Note: in Java IO Stream, byte Stream ends with Stream and character Stream ends with Reader/Writer.

FileInputStream read file

  • Read in the form of byte stream, and any file type can be read

  • Only one byte is read at a time, which is inefficient;

  • You can read a byte[len] array at one time to improve efficiency.

    FileInputStream fis = new FileInputStream("./src/io/text.txt");
    
    byte[] bytes = new byte[4]; // A can read up to 4 bytes
    int readCount = 0;
    while ((readCount = fis.read(bytes)) != -1) { // When reading to the end of the file, - 1 is returned. End cycle
    	System.out.print(new String(bytes, 0, readCount)); // Array, start position, length
        												   // How many bytes are read in and how many bytes are output.
        												   // Do not use new String(bytes), which will convert all the contents of bytes
    }
    

Fileoutputstream write file

  • Write in the form of byte stream. You can write any file type

  • It is inefficient to write only one byte at a time;

  • You can write out a byte[len] array at a time to improve efficiency.

    FileOutputStream fos = null;
    
    /**
    * fos created with this constructor will erase the contents of the original file every time it is written (it will be created automatically if the file does not exist)
    * Cannot append at the end of the original file
    */
    // fos = new FileOutputStream("./src/io/out.txt");
    
    /**
    * fos created with this constructor will not erase the contents of the original file, but will be appended at the end of the original file
    */
    fos = new FileOutputStream("./src/io/out.txt", true); // append = true;
    
    // 1. Write a byte
    fos.write(97); 
    
    // 2. Write all contents of a byte [] array
    byte[] bytes = {97, 98, 99, 100};
    fos.write(bytes); 
    // Write part of a byte [] array
    fos.write(bytes, 0, 3);
    
    // 3. Add String
    String s = "I am a Chinese, I am proud!";
    byte[] bs = s.getBytes();
    fos.write(bs);
    
    fos.flush(); // The output stream must be refreshed when it is used up
    fos.close();
    

FileReader reads files

  • Read in the form of character stream. You can only read ordinary text files (which can be opened with txt), but can't read pictures, audio, video, etc
  • Specific usage: replace bytes [] in FileInputStream with char [], and others are the same as FileInputStream

FileWriter writes files

  • It is written in the form of character stream. It can only write ordinary text files (which can be opened with txt), and can not operate pictures, audio, video, etc
  • Specific usage: replace bytes [] in FileOutputStream with char [], and others are the same as FileOutputStream

Buffer stream exclusive

BufferedReader reads files
  • The character input stream with buffer does not need a custom char [] array or a custom byte [] array.

  • When a flow is required in the construction method of a flow, the flow passed in is called node flow.

  • The external flow responsible for packaging is called packaging flow (or processing flow).

  • characteristic:

    • With its own buffer, it is more convenient to use;
    • readLine() can be read one line at a time (however, readLine() does not read line breaks at the end of the line)
    • When closing the flow, only the outer wrapper flow is closed, and there is no need to manually close the inner node flow (it has been implemented in the source code)
    /**
    * When a flow is required in the construction method of a flow, the flow passed in is called node flow.
    * The external flow responsible for packaging is called: packaging flow, and another name is: processing flow.
    * Like the current program: FiLeReader is a node flow.
    * BufferedReader Is the packaging flow / processing flow.
    */
    FileReader reader = new FileReader(".\\src\\io\\out2.txt");
    BufferedReader bfr = new BufferedReader(reader);
    
    String line = null;
    // Note: BFR Readline() can read a line of text, but it won't read in line breaks!
    while ((line = bfr.readLine()) != null) { // After reading the text content, null is returned
        // System.out.print(line); //  This will not wrap lines
    	System.out.println(line);
    }
    
    bfr.close(); // Only the wrapper flow of the outer layer is closed, and the node flow of the inner layer will be closed automatically (see the source code for details)
    
InputStreamReader transform stream
  • InputStreamReader: converts an input byte stream to an input character stream

    FileInputStream reader = new FileInputStream(".\\src\\io\\out2.txt"); // File byte input stream
    // For FileInputStream, InputStreamReader is a wrapper stream and FileInputStream is a node stream
    InputStreamReader fsr = new InputStreamReader(reader); // Convert stream: converts a byte stream to a character stream
    // For BufferedReader, InputStreamReader is a node stream and BufferedReader is a wrapper stream
    BufferedReader bfr = new BufferedReader(fsr); // Character input stream with buffer
    
    // Merge the above three lines (but it's not readable)
    // bfr = new BufferedReader(new InputStreamReader(new FileInputStream(".\\src\\io\\out2.txt")));
    
    String line = null;
    while ((line = bfr.readLine()) != null) { // null is returned after reading the text content
    	System.out.println(line);
    }
    
    bfr.close(); // Only the wrapper flow of the outer layer is closed, and the node flow of the inner layer will be closed automatically (see the source code for details)
    
  • OutputStreamWriter: converts an output byte stream to an output character stream

BufferedWriter write file
  • It has its own buffer. You do not need to specify byte [] or char []

  • characteristic:

    • With buffer, it is more convenient to use
    • When closing the flow, only the outer wrapper flow is closed, and there is no need to manually close the inner node flow (it has been implemented in the source code)
    final String path = ".\\src\\io\\bfout.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(path, true)); // append=true is the constructor parameter of FileWriter
    // OutputStreamWriter transform stream
    // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
    //				new FileOutputStream(path))); // append = true is the fileoutputstream constructor parameter
    bw.write("I come from China."); // You can write String type directly to the file
    
    bw.flush(); // The output stream must be refreshed
    bw.close(); // Just close the outer packaging flow
    

Data flow exclusive

DataOutputStream
  • Data can be written to a file along with the data type

  • Note: this file is not a normal text document. (this document can't be opened with notepad and will be garbled)

    final String path = ".\\src\\io\\dos.txt";
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(path));
    
    long l = 400L;
    float f = 2.0f;
    char c = 'a';
    boolean flag = false;
    // The data is written to the file along with the data type
    dos.writeLong(l);
    dos.writeFloat(f);
    dos.writeChar(c);
    dos.writeBoolean(flag);
    
DataInputStream
  • java.io.DataInputStream: data byte input stream

  • Files written by DataOutputStream can only be read by DataInputStreamTest:

    • And when reading, you must know the writing order in advance;
    • Data can be read normally only when the reading order needs to be consistent with the writing order.
    final String path = ".\\src\\io\\dos.txt";
    DataInputStream dis = new DataInputStream(new FileInputStream(path));
    // The read order must be consistent with the write order above
    long l = dis.readLong();
    float f = dis.readFloat();
    char c = dis.readChar();
    boolean flag = dis.readBoolean();
    

Using DataOutputStream to write files is a bit like encrypting data; Reading files using DataInputStream is a bit like decrypting data.

Standard output stream

  • PrintStream

    • java.io.PrintStream: Standard byte output stream, which is output to the console by default
    • You can change the output direction of the standard output stream, using system Setout method
    /**
    * Standard output stream, output to the console by default.
    */
    // Write together
    System.out.println("hello world!"); // Output to console
    // Write separately
    PrintStream ps = System.out;
    ps.println("hello kitty.");
    
    // You can change the output direction of the standard output stream
    final String path = ".\\src\\io\\log.txt";
    PrintStream ps2 = new PrintStream(path);
    System.setOut(ps2);
    
    System.out.println("hello zhangsan."); // At this point, output to the log file instead of the console
    System.out.println("hello world!");
    
  • PrintWriter

    • The standard character output stream is output to the console by default
    • You can change the output direction of the standard output stream, using system Setout method

Object flow exclusive

Serializable interface
  • The Serializable interface is a flag interface

    • There is no code in this interface
    public interface Serializable {}
    
  • The function of Serializable interface: it plays the role of identification

    • The Serializable flag interface is for Java virtual machine reference;
    • After the Java virtual machine sees this interface, it will automatically generate a serialized version number for this class.

    Recommendation: provide the serialization version number manually instead of automatically. (when such a class changes, it will not affect deserialization)

    • Otherwise, when the class is upgraded (changed) and deserialized according to the previous serialization file, it will fail and throw Java. Net io. InvalidClassException
  • The function of serialization version number: the identification of the class, which is used to distinguish the classification and ensure the uniqueness of the class.

  • How to classify Java: (2 methods)

    • (1) If the class name is different, it shall be distinguished according to the class name;
    • (2) If the class name is the same, it is distinguished according to the serialization version number.
Serialization and deserialization
  • Serialization: memory (object) - > hard disk (object)
    • Split object, serialize, use ObjectOutputStream
  • Deserialization: hard disk (object) - > memory (object)
    • Assemble objects, deserialize, and use ObjectInputStream
  • Classes that need serialization must implement the Serializable interface
  • Class, indicating that the field does not participate in serialization
  • The function of serialization version number: it is used to distinguish the classification and ensure the uniqueness of the class.
  • The serialized version number is provided manually rather than automatically.
    • When the serialization version number is manually provided, if the class (price increase) changes, the deserialization will not be affected;
    • Otherwise (when using the serialization version number automatically provided by the JVM), after the class is upgraded (changed), if it is still deserialized according to the previous serialization file, it will fail and throw Java io. InvalidClassException
  • Deserialization & when serializing multiple objects, you can use collections (put multiple objects into a list, and then serialize the list)

When providing the serialization version number manually, you can use IDEA/eclipse to generate the serialization version number of the class.

ObjectOutputStream
  • Used for object serialization

    public class Student implements Serializable { // Objects involved in serialization and deserialization must implement the Serializable interface. / / use eclipse to manually provide the serialization version number 	 private static final long serialVersionUID = -7788245228424997951L; 	 private int age; 	 private transient String name; // transient indicates that the field does not participate in serialization// Other methods and constructors omit} public static void main (string [] args) throws exception {final string path = "SRC \ \ IO \ \ student"; 	 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path)); 	 Student student = new Student(18, "Amy"); 	 oos.writeObject(student); //  serialize 			 oos.flush(); //  Output stream to refresh 	 oos.close();}
    
ObjectInputStream
  • Used for object deserialization

    final String path = "src\\io\\student";ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));Student student = (Student) ois.readObject(); // Deserialize system out. println(student); //  Student [age = 18, name = null], because name is modified with transient and does not participate in serialization
    

File class

  • File has nothing to do with the "four families" of IO streams, so file reading / writing cannot be completed through file.
    • It inherits from the Object class
    • public class File extends Object
  • File is an abstract representation of a file or directory pathname.
  • Common methods of File class:
methodeffect
boolean exists()Determine whether the File exists
boolean createNewFile()If the File does not exist, create a new one as a File
boolean mkdir()If the File does not exist, it is created as a directory
boolean mkdirs()If the File does not exist, it is created as multiple directories
String getAbsolutePath()Returns the absolute path corresponding to the File
String getParent()Returns the absolute path of the File parent path
File getParentFile()Returns the parent File of the File
File[] listFiles()Returns all files (files & directories) in the specified path
String getPath()Return the String corresponding to the abstract pathname (the toString of File calls the getPath() method)
String getName()Return File name (File name or directory name)
boolean isDirectory()Determine whether the File is a directory
boolean isFile()Judge whether File is a File

Copy file

  • Use FileInputStream and FileOutputStream to copy files
    • You can copy any type of file
  • Use FileReader and FileWriter to copy files
    • Note: only plain text files can be copied

These two programs add array After toString (chars), the loop is dead

  • Use File to copy all files in the directory recursively

    ... / / code is too long, reference file

IO + Properties read property configuration file

  • Use IO + Properties to read the property configuration file.
  • Usually, it is used in combination with JDBC or reflection.
  • In the property configuration file:
    • '=' left: key;
    • '=' right: value

String path = ".\\src\\io\\Dynamic node\\ioProperties\\userInfo.txt";FileReader reader = new FileReader(path);// Properties is equivalent to Map, but both key and value are of string type. Properties = new properties(); 		// Call the Load method of the properties object to Load the data in the file into the Map collection. properties.load(reader); // The data in the file is loaded into the Map collection along the pipeline, where the equal sign = key on the left and value on the right. / / take out the content in the property configuration file string name = properties getProperty("user"); System. out. println(name); 		 String passwd = properties.getProperty("password");System.out.println(passwd);

Keywords: Java JavaSE

Added by chrys on Fri, 21 Jan 2022 04:30:46 +0200