Detailed explanation of Java IO knowledge system

I amMr. Aojiaolu, a person who accumulates, learns, shares and grows.

If you think the content of the article is acceptable, I hope you will not hesitate to "One-click triple connection". I hope there are deficiencies in the article. Please add your doubts, insights and weird questions you encountered during the interview in the comment area

Table of contents

1. Knowledge system of Java IO framework

2. Java IO classification (transmission, operation)

1. IO understanding classification-from the perspective of transmission method

2. IO understanding classification - from the perspective of data operations

3. Java IO-Usage of common classes

1. File related

2. Byte stream related

3. Realize line-by-line output of the contents of a text file

4. Serialization & Serializable & transient

5. Network support in Java:

6、URL

7、Sockets

8、Datagram


1. Knowledge system of Java IO framework

Creating a good I/O system is not an easy task, and the difficulty seems to come from the need to cover all possibilities. Because there are not only various I/O sources (files, consoles, network connections, etc.), but also need to communicate with these I/O sources in many different ways (sequential, random, buffered, binary, character-by-character, line-by-line , by word) to communicate. The designers of Java class libraries solved this problem by creating a large number of classes.

 The most complete source code for detailed interpretation of io flow: Java8 I/O source code-catalog_Pan Weiwei's blog-CSDN blog

2. Java IO classification (transmission, operation)

1. IO understanding classification-from the perspective of transmission method

From the perspective of data transmission method or transportation method, the IO class can be divided into: byte stream and character stream

Byte stream (the overall structure is as follows, some derived classes are missing)

 Character stream (the overall structure is as follows, some derived classes are missing)

The difference between byte stream and character stream

  • The byte stream reads a single byte, and the character stream reads a single character (one character corresponds to different bytes depending on the encoding. For example, UTF-8 encoded Chinese characters are 3 bytes, and GBK encoded Chinese characters are 2 bytes. byte.)
  • The byte stream is used to process binary files (pictures, MP3, video files), and the character stream is used to process text files (which can be regarded as special binary files that use a certain encoding and can be read by humans).

Byte to character Input/OutputStreamReader/Writer

Encoding is converting characters into bytes, while decoding is reassembling bytes into characters. If the encoding and decoding processes use different encoding methods, garbled characters will appear.
  • In GBK encoding, Chinese characters occupy 2 bytes and English characters occupy 1 byte;
  • In UTF-8 encoding, Chinese characters occupy 3 bytes and English characters occupy 1 byte;
  • In UTF-16be encoding, Chinese characters and English characters both occupy 2 bytes.
The be in UTF-16be refers to Big Endian, which is Big Endian. Correspondingly, there is also UTF-16le, le refers to Little Endian, which is the little end. Java uses double-byte encoding UTF-16be. This does not mean that Java only supports this encoding method, but that the char type uses UTF-16be for encoding. The char type occupies 16 bits, which is two bytes. Java uses this double-byte encoding so that a Chinese or English character can be stored using a char.

2. IO understanding classification - from the perspective of data operations

From the perspective of data sources or operating objects, IO classes can be divided into:

 文件(file):FileInputStream、FileOutputStream、FileReader、FileWriter

Array([]):

  • Byte array (byte[]): ByteArrayInputStream, ByteArrayOutputStream

  • Character array (char[]): CharArrayReader, CharArrayWriter

Pipe operations: PipedInputStream, PipedOutputStream, PipedReader, PipedWriter

Basic data types: DataInputStream, DataOutputStream

Buffering operations: BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter

Print: PrintStream, PrintWriter

Object serialization and deserialization: ObjectInputStream, ObjectOutputStream

Conversion: InputStreamReader, OutputStreamWriter

3. Java IO-Usage of common classes

  • Disk operations: File

  • Byte operations: InputStream and OutputStream

  • Character operations: Reader and Writer

  • Object operations: Serializable

  • Network operations: Socket

1. File related

The File class can be used to represent file and directory information, but it does not represent the contents of the file. List all files in a directory recursively:

public static void listAllFiles(File dir) {
    if (dir == null || !dir.exists()) {
        return;
    }
    if (dir.isFile()) {
        System.out.println(dir.getName());
        return;
    }
    for (File file : dir.listFiles()) {
        listAllFiles(file);
    }
}

2. Byte stream related

public static void copyFile(String src, String dist) throws IOException {

    FileInputStream in = new FileInputStream(src);
    FileOutputStream out = new FileOutputStream(dist);
    byte[] buffer = new byte[20 * 1024];

    // read() 最多读取 buffer.length 个字节
    // 返回的是实际读取的个数
    // 返回 -1 的时候表示读到 eof,即文件尾
    while (in.read(buffer, 0, buffer.length) != -1) {
        out.write(buffer);
    }

    in.close();
    out.close();
}

3. Realize line-by-line output of the contents of a text file

public static void readFileContent(String filePath) throws IOException {

    FileReader fileReader = new FileReader(filePath);
    BufferedReader bufferedReader = new BufferedReader(fileReader);

    String line;
    while ((line = bufferedReader.readLine()) != null) {
        System.out.println(line);
    }
    // 装饰者模式使得 BufferedReader 组合了一个 Reader 对象
    // 在调用 BufferedReader 的 close() 方法时会去调用 Reader 的 close() 方法
    // 因此只要一个 close() 调用即可
    bufferedReader.close();
}

4、序列化 & Serializable & transient

Serialization is to convert an object into a byte sequence to facilitate storage and transmission.
  • Serialization: ObjectOutputStream.writeObject()
  • Deserialization: ObjectInputStream.readObject()
Static variables will not be serialized because serialization only saves the state of the object, and static variables belong to the state of the class.
Serializable
The serialized class needs to implement the Serializable interface. It is just a standard and does not need to implement any methods. However, if serialization is performed without implementing it, an exception will be thrown.
public static void main(String[] args) throws IOException, ClassNotFoundException {
    A a1 = new A(123, "abc");
    String objectFile = "file/a1";
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFile));
    objectOutputStream.writeObject(a1);
    objectOutputStream.close();

    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(objectFile));
    A a2 = (A) objectInputStream.readObject();
    objectInputStream.close();
    System.out.println(a2);
}

private static class A implements Serializable {
    private int x;
    private String y;


    A(int x, String y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "x = " + x + "  " + "y = " + y;
    }
}
transient
The transient keyword prevents some properties from being serialized.
The array elementData that stores data in ArrayList is decorated with transient because this array is dynamically expanded and not all the space is used, so there is no need for all contents to be serialized. By overriding the serialization and deserialization methods, it is possible to serialize only the part of the data that contains content in the array.
private transient Object[] elementData;

5. Network support in Java:

  • InetAddress: used to represent hardware resources on the network, that is, IP addresses;
  • URL: Uniform Resource Locator;
  • Sockets: Use TCP protocol to implement network communication;
  • Datagram: Implement network communication using UDP protocol.

InetAddress

There is no public constructor, and instances can only be created through static methods.
InetAddress.getByName(String host);
InetAddress.getByAddress(byte[] address);

6、URL

Byte stream data can be read directly from the URL.
public static void main(String[] args) throws IOException {


    URL url = new URL("http://www.baidu.com");

    /* 字节流 */
    InputStream is = url.openStream();

    /* 字符流 */
    InputStreamReader isr = new InputStreamReader(is, "utf-8");

    /* 提供缓存功能 */
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

    br.close();
}

7、Sockets

  • ServerSocket: Server-side class
  • Socket: client class
  • The server and client perform input and output through InputStream and OutputStream.

8、Datagram

  • DatagramSocket: Communication class
  • DatagramPacket: Data packet class

     

The series of articles continues to be updated. Search "Mr. Aojiaolu " on WeChat and reply [ Interview】Prepared interview materials for first-tier manufacturers.

Guess you like

Origin blog.csdn.net/cyl101816/article/details/126368517