This is the first day of my participation in Gwen Challenge.

When learning Java, I often get confused by various IO streams. There are many kinds of streams, and it is easy to get confused without categorizing them. This article will try to figure out the classification and use of IO streams, and then you can tell others about streams.

What is flow:

The channel for transferring data between memory and storage devices

According to the different flow direction, it can be divided into:

  • Input stream: Reads the contents of a storage device into memory
  • Output stream: Writes the contents of memory to the storage device

As shown above:The input stream is used to read the file into memory, and the output stream is used to write the modified content to the file

According to different units, can be divided into

  • Byte stream: Reads and writes all data in bytes
  • Character stream: Reads and writes text data in character units

According to different functions, it can be divided into:

  • Node flow: Has the read and write function of transmitting data
  • Filter flow: Enhanced functionality on top of node flow

Class structure for byte streams

The top two abstract classes

  • InputStream: byte InputStream (read(), read(byte[] b), read(byte[] b,int off,int len))
  • OutputStream: byte OutputStream (write(), write(byte[] b), write(byte[] b,int off,int len))

Use of file byte stream

  1. FileInputStream: byte stream that reads files into memory for custom operations
  2. FileOutputStream: A byte stream that writes to a file. The byte stream rewrites the file after the operation, either to a new file or overwrites the original file

Use FileInputStream:

Public static void main(String[] args) throws IOException {// Create a byte input stream FileInputStream FileInputStream = new FileInputStream("d:\\aaa.txt"); Fileinputstream.read (); int data = 0; while((data = fileInputStream.read())! =-1){ System.out.println(data); } // Turn off the byte stream fileInputstream.close (); }Copy the code

The use of FileOutputStream and the ability to copy files using both

Public static void main(String[] args) throws IOException {// Copy // define the input stream FileInputStream fis = new FileInputStream("d:\\1.jpg"); FileOutputStream fos = new FileOutputStream("d:\\2.jpg"); Byte [] buf = new byte[1024]; int c = 0; While ((c = fis.read(buf))! =-1){ fos.write(buf,0,c); } // Close the stream fis.close(); fos.close(); }Copy the code

Byte buffer stream:

BufferedInputStream, BufferedOutputStream, will create a buffer, put the file in the buffer, and then read or write it out at once, which has two benefits

  • This improves I/O efficiency and reduces disk access times, which are time-consuming and resource consuming.
  • The data is stored in a buffer, and the flush call writes the contents of the buffer to the file at once, or it can be closed (flush is called internally).

If you look at the source code, you can see that BufferedInputStream’s default buffer size is 8K, as is BufferedOutoutStream

class BufferedInputStream extends FilterInputStream {

    private static int DEFAULT_BUFFER_SIZE = 8192;

    /**
     * The internal buffer array where the data is stored. When necessary,
     * it may be replaced by another array of
     * a different size.
     */
    protected volatile byte buf[];

 }
Copy the code

Byte buffered streams are used in much the same way as regular byte streams, except that the classes created are different. It also needs to wrap a basic byte stream when it is created, which is also embodied in the decorator pattern, encapsulating the original object and adding some other behavior.

FileInputStream1 = new FileInputStream("d:\ aaa.txt"); // Create bufferstream with fileInputStream1 as argument, Wrap it and add behavior method BufferedInputStream BufferedInputStream = new BufferedInputStream(fileInputStream1); // Use the read() method to read int data1 = 0 byte by byte; while((data1 = bufferedInputStream.read())! =-1){ System.out.println((char)data1); } / / * * * * * * * * * * * * * * * * * more bytes read together * * * * * * * * * * * * * / / custom buffer read even a byte [] b1 = new byte [128]. int count1 = 0; while((count1 = bufferedInputStream.read(b1))! = 1) {System. Out. Println (new String (b1, 0, count1)); } bufferedInputStream.close();Copy the code

BufferedOutputStream writes to the buffer using write and to disk using Flush. If the flush method is not called, it is only written to the buffer, not to the disk file. The close method calls itself flush.

Public static void main(String[] args) throws IOException {// Create a bufferoutput stream FileOutputStream FileOutputStream = new FileOutputStream("d:\\buffer.txt"); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); for(int i=0; i<10; I++) {/ / the buffer (default 8 k) bufferedOutputStream. Write (" abcdefg \ r \ n ". GetBytes ()); / / flushed to disk bufferedOutputStream. Flush (); } / / close (internal) will call flush method bufferedOutputStream. Close (); }Copy the code

Object flow:

ObjectOutputStream ObjectInputStream. The process of transferring an object using a stream is called serialization (the process of writing an object into a stream to write) and deserialization (the process of reading and reconstructing an object read). There are a number of IO operations that go along with it. There are several benefits to using object streams:

  • Enhanced buffer functionality
  • Eight basic data types and string capabilities have been enhanced
  • Improved reading and writing of objects (readObject() reads an Object from the stream, writeObject (Object obj) writes an Object to the stream)
Implementation of serialization and deserialization:

Start by creating instance classes for serialization and deserialization

Public class Student implements Serializable{/** * Serializable public class Student implements Serializable{/** * Serializable public class Student implements Serializable{/** * private static final long serialVersionUID = 1L; int age; String name; . }Copy the code

Implement object serialization and deserialization operations:

Public static void main(String[] args) throws IOException {// serialize: FileOutputStream FileOutputStream = new FileOutputStream("d:\\stu.bin"); ObjectOutputStream = new ObjectOutputStream(fileOutputStream); ObjectOutputStream = new ObjectOutputStream(fileOutputStream); // Create a new object (this instance needs to implement Serializable to indicate that the object can be serialized) Student stu = new Student(12,"zs"); / / write file serialized objectOutputStream. WriteObject (stu); // Close the output stream (internally called flush) objectOutputStream.close(); FileInputStream FileInputStream = new FileInputStream("d:\\stu.bin"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); / / read object (deserialization) Student Student = (Student) objectInputStream. ReadObject (); Objectinputstream.close (); System.out.println(student.toString()); }Copy the code
When implementing object serialization and deserialization, note the following:
  • Serialization classes must implement the Serializable interface
  • Object properties in serialized classes also need to implement the Serializable interface
  • Serialization version ID (serialVersionUID), which ensures that the serialized class is the same as the deserialized class
  • With transient modifier properties, this property cannot be serialized
  • Static properties cannot be serialized. Static properties belong to a class and not to an object
  • Serializing multiple objects can be done with a List collection

Characters of the flow

Character encoding and character set are two basic concepts that many developers are familiar with, but few of them can describe accurately.

A character set is a collection of all abstract characters supported by a system. A character is a variety of characters and symbols, including national characters, punctuation marks, graphic symbols, numbers, etc. But when we talk about the character set, we really mean the coded character set, and the coded character set means that every character in the coded character set corresponds to a unique code value.

The definition of character encoding: is the conversion relationship between the characters of the encoding character set and the actual stored value. When the encoding mode and decoding mode are different, garbled characters will appear

Common coded character sets are:

  • Iso-8859-1: contains in addition to ASCII, also includes western European, Greek, Thai, Arabic, Hebrew corresponding character symbols
  • Utf-8: Variable length character encoding for Unicode code tables (three bytes per Chinese character)
  • GB2312: Simplified Chinese
  • GBk: simplified Chinese version of expanded GB2312
  • BIG5: Traditional Chinese

The class structure of a character stream

File character stream:

FileReader:

  • Read (): Reads a single character
  • Read (char[] c) : Reads multiple characters from the stream, stores the read contents into the C array, returns the actual number of characters read; If the end of the file is reached (read), -1 is returned

Read a file using a file character stream:

Public static void main(String[] args) throws IOException {// Create FileReader FileReader fReader = new FileReader("d:\\h.txt"); Int data = 0; while((data = fReader.read())! =-1){ System.out.println((char)data); Char [] buf = new char[128]; int count = 0; while((count = fReader.read(buf))! =-1){ System.out.println(new String(buf,0,count)); } fReader.close(); }Copy the code

FileWriter:

  • Write (String STR) Writes more than one character at a time, writing all the characters in the B array to the output stream

Write to a file using a file character stream:

Public static void main(String[] args) throws IOException {// Create FileWriter FileWriter fWriter = new FileWriter("d:\\h.txt"); for(int i = 0; i<10; i++){ fWriter.write("abcdefg"); fWriter.flush(); } fWriter.close(); }Copy the code
  • Use FileReader and FileWriter to copy files (only text files, not other binaries such as images/audio files) :
Public static void main(String[] args) throws IOException {// Create FileReader FileReader fReader = new FileReader("d:\\h1.txt"); FileWriter fWriter = new FileWriter("d:\\h2.txt"); int data = 0; // Write while((data = freader.read ())! =-1){ fWriter.write(data); } fReader.close(); fWriter.close(); }Copy the code

Character buffer stream:

  • BufferedReader: Reads text from the character input stream, buffering individual characters for efficient reading
  • BufferedWriter: Writes text to the character output stream, buffering individual characters to provide efficient writing of individual characters, arrays, and strings.
  1. Read files using buffered streams:
Public static void main(String[] args) throws IOException {// Create bufferstream FileReader FileReader = new FileReader("d:\ h.txt");  BufferedReader bReader = new BufferedReader(fileReader); Char [] buf = new char[1024]; int count = 0; while((count = bReader.read(buf))! =-1){ System.out.println(new String(buf,0,count)); } // Use readLine to read a String line = null; while((line = bReader.readLine())! =null){ System.out.println(line); } bReader.close(); }Copy the code
  1. Write files using buffered streams:
Public static void main(String[] args) throws IOException {// Create FileWriter FileWriter = new FileWriter("d:\\w.txt"); BufferedWriter bWriter = new BufferedWriter(fileWriter); // write for(int I = 0; i<10; i++){ bWriter.write("abcdefg"); // Write the newLine character bwriter.newline (); bWriter.flush(); } bWriter.close(); }Copy the code

Transformation flows:

InputStreamReader/OutputStreamWriter:

  • Byte streams can be converted to character streams (InputStreamReader converts byte input streams to character input streams, OutputStreamWriter converts byte output streams to character output streams)
  • You can set the encoding of characters

InputStreamReader is a bridge from byte flow to character stream. It reads bytes with a specified charset and decodes them into characters. The character set it uses can be specified by name or explicitly given. OutputStreamWriter: a bridge for character flow to the byte stream

Public static void main(String[] args) throws IOException {// Create FileInputStream fis = new FileInputStream("d:\\a.txt");  InputStreamReader isr = new InputStreamReader(fis, "utF-8 "); Int data = 0; while((data = isr.read())! =-1){ System.out.println((char)data); } isr.close(); FileOutputStream fos = new FileOutputStream("d:\\b.txt"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos,"utf-8"); // write for(int I = 0; i<10; i++){ outputStreamWriter.write("abcdefg"); } // Close outputStreamWriter.close(); }Copy the code

File API related to files

Represents a file or folder in a physical drive letter. The common methods are as follows:

  • CreateNewFile ()– Creates a file
  • Mkdir ()– creates a new directory
  • Delete ()– Deletes a file or an empty directory
  • Exists ()– Checks whether the object represented by the file object exists
  • GetAbsoulutePath ()– The absolute path to get the file
  • GetName ()– Gets the name
  • GetParent ()– Gets the directory where the file is located
  • IsDirectory ()– Whether it is a directory
  • IsFile () — Whether it is a file
  • Length ()– Gets the length of the file
  • ListFiles ()– Gets all the contents of the directory
  • RenameTo () — Changes the file name

conclusion

This article only shows how IO framework is applied from the basic use. Through this article, we can understand IO framework from the macro view, and have a clearer understanding of the classification and application of IO framework. Of course, more use is to see API, and flexible use in the work can have a deeper understanding. I’ll take a deeper look at IO from within the application.