[IO] JavaIO stream: byte stream, character stream, buffer stream, conversion stream, serialization stream, etc.

Personal profile: Rising star creator in the Java field; Alibaba Cloud technology blogger, star blogger, expert blogger; currently on the road to Java learning, recording the learning process ~
Personal homepage: .29.’s blog
Learning Community: Go in and have a look~

IO stream

  • JavaIO
    • 1. Get to know IO
    • 2. FileOutputStream(write)
    • 3. FileInputStream(read)
    • 4. Java encoding and decoding
    • 5. Character stream
      • 1) FileReader
      • 2)FileWriter
    • 6. Buffered stream
      • 1) Byte buffer stream
      • 2)Character buffer stream
    • 7. Conversion stream (a type of character stream)
    • 8. Serialization stream/Deserialization stream
    • 9. Print stream
    • 10. Compressed stream/decompressed stream

Java IO

1. Understanding IO

IO stream:

  • Direction of flow Division:
    • Input stream: read
    • Output stream: write out
  • File type division of stream operations:
    • Byte stream: can read all file types
      • InputStream: byte input stream
      • OutputStream: byte output stream
    • Character stream: can read plain text files
      • Reader: character input stream
      • Writer: character output stream

2. FileOutputStream(write)

Usage steps:

  • Create byte output stream object

    • Parameters: Path/File object represented by string
    • The file does not exist, or a new one is automatically created, but the parent path needs to exist.
    • If the file already exists, it will be overwritten
  • Write data

    • The parameters in writer() are of type int, and the actual content written to the file is the ASCII code value corresponding to the integer.
    • Three ways:
      • void write(int b): Write one byte of data at a time
      • void write(byte[] b): Write data one byte array at a time
      • void write(byte[] b,int off,int len): Write part of the data of an array at a time (parameters: array, starting index, number)
  • Release resources

    • Resources need to be released after each use of the stream
  • First introduction case:

    • public class FileOutputStreamDemo {<!-- -->
          public static void main(String[] args) throws IOException {<!-- -->
              //Get the output stream object
              FileOutputStream fos = new FileOutputStream("D:\JavaData\myIO\a.txt");
              //write operation
              fos.write(97);
              //Close the resource
              fos.close();
          }
      }
      
  • Newline character:

    • Windows: \r\\
    • Linux: \\
    • Mac: \r
  • Continuation:

    • When the written file exists, the content will generally be overwritten. If you want to continue writing, you need to set parameters when creating the file output stream object.

    • //Parameter 1: path
      //Parameter 2: Whether to continue writing: true to continue writing false: overwrite
      FileOutputStream fos = new FileOutputStream("D:\JavaData\myIO\a.txt",true);
      

3. FileInputStream(read)

Usage steps:

  • ①Create a byte input stream object
    • If the read file does not exist, an error FileNotFoundException will be reported directly.
  • ②Read data
    • Read one byte at a time, and the read content is the int number corresponding to the ASCII code of the data.
    • Read to the end of the file, read() returns -1
    • public int read(): Read one byte of data at a time
    • public int read(byte[] buffer): Read one byte array data at a time
  • ③Release resources
    • Every time a stream is used, resources must be released.
  • Avoid garbled characters:
      1. Reading text file without using byte stream
      2. Use the same code table and the same encoding method when encoding and decoding

Loop reading:

  • Example:

    • Read one byte at a time
    • public class FileInputStreamDemo {<!-- -->
          public static void main(String[] args) throws IOException {<!-- -->
              //Create file input stream object
              FileInputStream fis = new FileInputStream("D:\JavaData\myIO\a.txt");
              //Loop reading (read one byte at a time)
              int b;
              while((b = fis.read()) != -1){<!-- -->
                  System.out.print((char)b);
              }
              //Release resources
              fis.close();
          }
      }
      

4. Java encoding and decoding

Encoding and decoding methods in Java:

  • coding:
  • public byte[] getBytes(): Use default encoding
  • public byte[] getBytes(String charsetName): Encode using the specified method
  • decoding:
  • String(byte[] bytes): Only use the default method for decoding
  • String(byte[] bytes,String charsetName): Use the specified method to decode

5. Character stream

Character stream:

  • Character stream: byte stream + character set
  • Features
    • Input stream: read one byte at a time, when encountering Chinese, read multiple bytes at a time
    • Output stream: The bottom layer will encode the data according to the specified encoding method, turn it into bytes and then write it to the file.
  • Applicable to: reading and writing plain text files.

1) FileReader

Usage steps:

  • ①Create a character input stream object
    • public FileReader(File file): Create a character input stream associated with a local file
    • public FileReader(String pathname): Create a character input stream associated with a local file
      • If the file does not exist, an error will be reported
  • ②Read data
    • public int read(): Read data and return -1 to the end
    • public int read(char[] buffer): Read the data of the array length at a time, and return -1 after reading to the end
      • The empty parameter method reads by bytes. When reading Chinese, multiple bytes are read at a time, decoded after reading, and an integer is returned.
      • Read to the end of the file, read() returns -1.
  • ③Release resources
    • public int close(): Release/close resources
  • Principle
    • When creating a character stream object: the underlying associated file and creates a buffer (array of length 8192)
    • When reading data:
        1. Determine whether there is data in the buffer that can be read,
        2. There is no data in the buffer. Get the data from the file and write it into the buffer. Try to fill the buffer as much as possible each time. If there is no data in the file, return -1
        3. There is data in the buffer, read the buffer directly
        4. Empty parameter read() – reads one byte at a time, Chinese reads multiple bytes at a time, decodes and converts the bytes into decimal
        5. Read() with parameters – combines the three steps of reading bytes, decoding and forced conversion, and stores the converted characters into a character array

2) FileWriter

Use

  • ①Create character output stream object
    • public FileWriter(File file): Create a character output stream associated with a local file
    • public FileWriter(String pathname): Create a character output stream associated with a local file
    • public FileWriter(File file,boolean append): Continuation mode, creates a character output stream associated with a local file
    • public FileWriter(String pathname,boolean append): Continuation mode, creates a character output stream associated with a local file
      • If the file does not exist, a new file will be automatically created, but the parent path must exist.
      • If the file exists, it will be overwritten and parameters need to be passed in. If overwriting is not required, the continuation switch can be turned on (true).
  • ②Write the data:
    • void write(int c): Write a character (the output integer corresponds to the ASCII code)
    • void write(String s): Write a string
    • void write(String str,int off,int len)Write a string, specify the starting index and output length
    • void write(char[] cbuf): Write the data of a character array
    • void write(char[] cbuf,int off,int len): Write the data of a character array, specify the starting index and output length
  • ③Close resources
    • Write buffer data to file before closing
    • The buffer can be flushed manually with flush() – the buffer data is written to the file and the buffer is cleared.

6. Buffered stream

Buffered stream:

  • buffered stream
    • ①Byte buffer stream
      • 1) BufferedInputStream – byte buffered input stream
      • 2) BufferedOutputStream – byte buffered output stream
    • ②Character buffer stream
      • 1) BufferedReader – character buffered input stream
      • 2) BufferedWriter – character buffered output stream

1) Byte buffer stream

Byte buffer stream:

  • use:
    • public BufferedInputStream(InputStream is): Pack the basic stream into an advanced stream to improve the efficiency of reading data.
    • public BufferedOutoutStream(OutputStream os): Pack the basic stream into an advanced stream to improve the efficiency of writing data.
  • principle:
    • The underlying layer comes with a buffer (8KB) of length 8192 bytes to improve performance.
    • The byte stream itself does not have a buffer, and buffering the stream can significantly improve performance.

2) Character buffer stream

Character buffer stream:

  • Use
    • public BufferedReader(Reader r): Pack the basic stream into an advanced stream to improve the efficiency of reading data (character buffer input stream object)
    • public BufferedWriter(Writer r): Pack the basic stream into an advanced stream to improve the efficiency of writing data (character buffer output stream object)
      • The bottom layer comes with a buffer (16KB) of 8192 character array length to improve performance (buffer data is used in memory, which is fast)
      • The character stream has its own buffer. The buffer stream does not significantly improve the efficiency of the character stream. However, the main significance of the character buffer stream to the character stream is: readLine() and newLine()
  • Character buffer input stream unique methods:
    • public String readLine(): Read a line of data. If there is no data at the end, null will be returned.
  • Character buffer Output stream unique methods:
    • public void newLine(): Line break operation, cross-platform

7. Conversion stream (a type of character stream)

Conversion stream:

  • Conversion stream: It is the bridge between character stream and byte stream.
    • InputStreamReader – byte conversion input stream
      • public InputStreamReader(InputStream in): Converts a byte input stream into a character input stream.
    • OutputStreamWriter – byte conversion output stream
      • public OutputStreamWriter(OutputStream out): Convert character output stream to byte output stream.
  • Function: When the byte stream wants to use the methods in the character stream, the conversion stream can be used.

8. Serialization stream/deserialization stream

Serialization stream (object operation output stream):

  • Function: Java objects can be written to local files.

  • Use:

    • Construction method – public ObjectOutputStream(OutputStream out): Pack the basic byte output stream into a serialized stream (obtain the serialized stream object)
    • Member method – public final void writeObject(Object obj): Serialize (write) the object to a local file
      • If you directly use the object output stream to save the object to a file, an error NotSerializableException will be reported. The JavaBean class needs to implement the Serializable interface, indicating that such objects are serializable.

Deserialization stream (object operation input stream):

  • Function: You can read objects serialized into local files into the program.

  • use:

    • Construction method – public ObjectInputStream(InputStream in): Pack the basic byte input stream into a deserialization stream (get the deserialization stream object)
    • Member method – public Object readObject(): Read the object serialized into the local file into the program
  • The JavaBean class needs to implement the Serializable interface to indicate that such objects are serializable. At the same time, to prevent the change of Java version number from causing the serialization version number to be inconsistent and deserialization failure, we should manually set a serialization version number for JavaBean:

    • private static final long serialVersionUID = -6357601841666449654L;
      

9. Print stream

Print stream:

  • print stream

    • Byte print stream PrintStream
    • Character print streamPrintWriter
  • Byte print stream-PrintStream

    • Construction method (get byte print stream object):

    • public PrintStream(OutputStream/File/String): associated byte output stream/file/file path

    • public PrintStream(String fileName,Charset charset): Specify character encoding

    • public PrintStream(OutputStream out,boolean autoFlush): Set automatic refresh

    • public PrintStream(OutputStream put,boolean aytoFlush,Charset charset): Specify character encoding and automatically refresh

    • Member methods:

    • public void write(int b): Write out the specified byte

    • public void println(Xxx xxx): Unique method: print arbitrary data, automatically refresh, and automatically wrap lines

    • public void print(Xxx xxx): Unique method: print any data without line breaks

    • public void printf(String format,Object... args): Unique method: print statement with placeholder, no line breaks

      • There is no buffer at the bottom of the byte stream, and there is no change whether automatic refresh is enabled or not.
  • Character printing stream-PrintWriter

    • For method usage, refer to the byte print stream mentioned above (just replace the constructor method name PrintStream with PrintWriter, and the member method names and usage methods are the same)
  • Features:

    • The print stream only operates on the file destination and does not operate on the data source, so it can only be used as an output stream.
    • There is a unique writing method that can write the data as it is.
    • There is a unique write method that can realize automatic refresh and automatic line wrapping (write + refresh + line wrap)

10. Compressed stream/decompressed stream

Decompress stream:

  • **Essence of decompression:**Copy each ZipEntry object in the compressed package to another local folder according to the hierarchy.

  • Use:

    • public ZipInputStream(InputStream in): Constructor to wrap a normal byte input stream into a decompressed stream.
    • ZipInputStream.getNextEntry(): Gets the entry object in the compressed package and returns null after reading to the end.
  • Case:

    • public class ZipStreamDemo {<!-- -->
          public static void main(String[] args) throws IOException {<!-- -->
              //Decompress stream example
      
              //File object, representing the file that needs to be decompressed
              File src = new File("D:\JavaData\myIO\aa.zip");
              //File object, indicating the decompressed path
              File dest = new File("D:\JavaData\myIO");
      
              unZip(src,dest);//Decompress
          }
      
          //Create a method for decompression
          public static void unZip(File src,File dest) throws IOException {<!-- -->
              //Create decompression stream object
              ZipInputStream zip = new ZipInputStream(new FileInputStream(src));
      
              //Read each decompressed entry object
              ZipEntry entry;
              while((entry = zip.getNextEntry()) != null){<!-- -->
                  //If it is a folder, create a new folder in the unzipped directory
                  if(entry.isDirectory()){<!-- -->
                      File file = new File(dest,entry.toString());
                      file.mkdirs();
                  }else{<!-- -->
                      //If it is a file, output to the specified directory
                      FileOutputStream fos = new FileOutputStream(new File(dest, entry.toString())); //Output stream
                      int i;
                      while((i = zip.read()) != -1){<!-- -->
                          //write to destination
                          fos.write(i);
                      }
                      fos.close(); //Close the output stream
                      zip.closeEntry(); //Close the current entry
                  }
              }
              zip.close();
          }
      }
      

Compressed stream:

  • ZipOutputStream

    • Compress a single file: