[Interview with Experts]——JavaIO (23 questions)


Insert image description here
Insert image description here

1. What is Java IO?

Java IO (Input/Output) is an API for handling input and output operations, which allows programs to interact with data from the outside world.

2. How to understand IO flow from the data transmission method?

It can be classified along three different dimensions:

• 1. According to the direction of the stream (output and input are divided from the perspective of the memory where the program is located)
• Input stream: only data can be read from it [mainly InputStream and Reader are used as base classes]

• Output stream: data can only be written to it [mainly outputStream and Writer as base classes]

• 2. Divide according to the operation granularity of the flow

• Byte stream: takes bytes as unit and can operate on any data [Mainly using InputStream and outPutStream as base classes]

• Character stream: Taking characters as units, it can only operate pure character data, which is more convenient [mainly using Reader and Writer as base classes]

• 3. Divide according to the roles of flows

• Node stream: A stream that can read/write data from/to a specific IO device (such as disk, network), also called [low-level stream, mainly composed of]

• Processing stream: used to connect and encapsulate an existing stream, and realize the data read/write function through the encapsulated stream, also called [advanced stream]

3.What design patterns are used in Java IO design?

  • Single Responsibility Principle: This is an important object-oriented design principle, which requires that a class should have only one responsibility. In Java IO, different classes are responsible for different I/O operations. For example, InputStream is responsible for reading bytes, and OutputStream is responsible for writing bytes. This is in line with the single responsibility principle.
  • Decorator Pattern: Buffered streams (such as BufferedReader and BufferedWriter) and filtered streams (such as GZIPInputStream and GZIPOutputStream) in Java IO adopt the decorator pattern. These classes enhance the functionality of I/O streams through composition rather than extension through inheritance.
BufferedReader br = new BufferedReader(new FileReader("file.txt"));

Here, BufferedReader decorates FileReader to provide the function of buffered reading.

  • Strategy Pattern: The Charset and CharsetEncoder/CharsetDecoder classes in the Java IO library adopt the Strategy Pattern. They allow you to encode and decode characters according to different character encoding strategies.
Charset utf8 = Charset.forName("UTF-8");
CharsetEncoder encoder = utf8.newEncoder();

Here, the Charset object acts as a strategy object, and CharsetEncoder performs encoding operations according to different strategies.

  • Observer Pattern: Classes such as File and DirectoryStream in the Java IO library can be used to monitor files and directories in the file system. These classes allow you to register observers to listen for file system events, conforming to the Observer pattern.
Path directory = Paths.get("my_directory");
WatchService watchService = FileSystems.getDefault().newWatchService();
directory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

Here, WatchService acts as an observer and monitors the creation events of files in the file system.

4. What is Java NIO?

Java NIO: Synchronous and non-blocking, the server implementation mode is one request and one thread, that is, the connection request sent by the client will be registered on the multiplexer, and the multiplexer will only start when there is an I/O request on the connection. A thread is processed.

5.When is BIO?

Java BIO: Synchronization and blocking, the server implementation mode is one connection and one thread, that is, when the client has a connection request, the server needs to start a thread for processing. If the connection does not do anything, it will cause unnecessary thread overhead. Of course, it can Improved through thread pool mechanism.

6.What is AIO?

Java AIO (NIO.2): Asynchronous and non-blocking, the server implementation mode is one valid request and one thread. The client's I/O requests are completed by the OS first and then notify the server application to start the thread for processing.

7.How do you understand synchronous IO and asynchronous IO?

  • Synchronous I/O:
    blocking mode: In synchronous I/O, when an I/O operation is initiated, the calling thread will be blocked until the operation is completed or an error occurs. This means that the thread will wait forever, unable to perform other tasks.
    Sequential execution: Synchronous I/O operations are usually executed sequentially in the order in which they are initiated. Each operation must wait for the previous operation to complete before continuing.
    Resource usage: Synchronous I/O requires allocating a thread to handle each I/O operation. If there are a large number of concurrent connections, a large amount of thread resources will be consumed.

  • Asynchronous I/O:
    Non-blocking mode: In asynchronous I/O, when an I/O operation is initiated, the calling thread will not be blocked and can continue to perform other tasks without waiting for the operation to complete.
    Concurrency: Asynchronous I/O allows multiple I/O operations to be initiated at the same time and processed in the background, so it has higher concurrency.
    Callback mechanism: Asynchronous I/O usually uses a callback function to handle notification of completion of the I/O operation. When the I/O operation is completed, the system calls the pre-registered callback function instead of waiting for the thread.
    Complexity: Asynchronous I/O programming is relatively more complex because it needs to deal with complex issues such as callback functions and state management.

8.What do you understand between blocking IO and non-blocking IO?

Blocking IO: When a thread performs an I/O operation, it will block the thread until the operation is completed.
Non-blocking IO: The calling thread will not be blocked and can continue to perform other tasks without waiting for the operation to complete. Allows one thread to manage multiple channels (connections).

9.What is the difference between input stream and output stream in IO?

10.What is the difference between byte stream and character stream?

Answer: When reading a byte stream, one byte is returned after reading one byte; the byte stream uses a byte stream to read one or more bytes (the corresponding number of bytes in Chinese is two, in the UTF-8 code table in is 3 bytes) time. First checks the specified encoding table and returns the characters found. Byte stream can handle various types of data such as pictures, MP3, AVI video files, etc., while character stream can only handle character data. In addition to byte streams, character streams must be used first as long as plain text data is processed. Byte stream mainly operates byte type data, with byte and array as the standard. The main operation categories are OutputStream and Inputstream. The unit of character stream processing is 2-byte Unicode characters. It operates characters, character arrays or strings respectively. Byte stream Processing unit 1 operates on bytes and bytes of byte arrays. Therefore, the character stream is made by Java converting bytes into virtual machine 2-byte Unicode characters are unit characters, so it has good support for multiple languages! If it is audio files, pictures and songs, it is best to use byte stream. If it's related to Chinese (text), it's better to use character stream. In the program, one character is equal to two bytes. Java provides two categories, Reader and Writer, that specialize in operating character streams.

11.How many types of Java traffic are there?

Answer:
(1) According to the flow direction: input stream (inputStream) and output stream (outputStream);
(2) According to the implementation function: node stream (can read and write data from or to a specific place (node). Such as FileReader) and Processing stream (is the connection and encapsulation of existing streams, which realizes data reading and writing by calling the function of the encapsulated stream. Such as BufferedReader. The structural method of processing streams always takes other stream objects as parameters. A stream object is packaged multiple times by other streams , called stream link);
(3) According to the unit of data processing: byte stream and character stream. Inherits byte streams InputStream and OutputStrea, and InputStreamreader inherits character streams and OutputStreamWriter.

12.How to convert byte stream into character stream?

Answer: Byte input flow Character input flow InputStreamReader This structural function can implement and transmit InputStream objects.
The byte output stream and character output stream can be implemented and transmitted through the OutputStreamWriter structure function.

13.How to serialize a java object into a file?

Answer: Classes that can be serialized in Java must first implement the Serializable interface. There is no abstract method, but it only serves as a marker.

  public class Test {
    
    
        public static void main(String[] args) throws Exception {
    
    
            // 对象输出流
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("D://obj")));
            objectOutputStream.writeObject(new User("zhangsan", 100));
            objectOutputStream.close();
            // 对象输入流
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("D://obj")));
            User user = (User) objectInputStream.readObject();
            System.out.println(user);
            objectInputStream.close();
        }
    }

14.What is java serialization?

Answer: Serialization is a mechanism for processing object streams. The so-called object stream is the content of the streaming object. Streamed objects can be read and written, and can also be transferred between networks. Serialization is to solve problems caused by object stream read and write operations.

15.How to implement java serialization?

Answer: To implement serialization, you will need to implement the serialization class Serializable interface. The interface has no implemented methods. Implements Serializable is just to mark the object as serializable, and then use the output stream (such as: File Output Stream) to construct an Object Output Stream. ) object, then use the write Object(Object obj) method of the Object Output Stream object to write out the obj object (that is, save its state). If you want to restore it, use the input stream.

16.What is Filter stream?

Answer: Filter Stream is the main function of IO stream, which is used to add some additional functions to the existing traffic, such as adding lines to the target file that do not exist in the source file or copying performance.

17.What filter streams are available?

Answer: In http://java. Stream mainly consists of four available filter packages. Two byte filter streams, two character filter streams. They are Filter Input Stream, Filter Output Stream, Filter Reader and Filter Writer. These categories are abstract and cannot be instantiated.

18.Explain java.io.Serializable interface?

Answer: Its serialization function can be enabled by implementing the interface of class java.io.Serializable. A class that does not implement this interface will not be able to serialize or deserialize any of its state.

19.How to implement object cloning?

Answer: There are two ways (1) Implement the Cloneable interface and override the clone() method in the Object class (2) Implement the Serializable interface to achieve true deep cloning through object serialization and deserialization.

20.What is the difference between input stream and output stream in Java?

Input streams are used to read data from a data source (such as a file or network), and output streams are used to write data to a destination (such as a file or network).

21.How many types of streams are there in Java?

Divided into character stream and byte stream.

22. How to understand IO flow from the perspective of data operations?

Insert image description here

23. What are the differences between BIO, NIO and AIO and their applicable scenarios?

  • BIO (Blocking I/O):
    Blocking model: BIO is an I/O operation based on the blocking model, which means that when a thread performs an I/O operation, it will block until the operation is completed.
    Synchronicity: In BIO, all I/O operations are synchronized, one thread reads or writes to a connection until completed.
    Applicability: It is suitable for situations where the number of connections is small and the data interaction of each connection is frequent, but the performance is not good in high concurrency environments.

  • NIO (Non-blocking I/O):
    Non-blocking model: NIO adopts a non-blocking model, allowing one thread to manage multiple channels (connections).
    Selector: NIO introduces the concept of selector. Through the selector, a thread can monitor events on multiple channels, such as read ready, write ready, etc.
    Buffer: NIO uses buffers to store data, which can improve I/O efficiency.
    Applicability: It is suitable for situations where a large number of connections need to be processed and there are a large number of connections, but the data interaction of each connection is relatively small, such as Web servers.

  • AIO (Asynchronous I/O):
    Asynchronous model: AIO adopts an asynchronous model, which allows a thread to not be blocked when performing I/O operations, and will notify the application when the operation is completed.
    Callback mechanism: AIO uses a callback mechanism to handle notification of completion of I/O operations.
    Applicability: Suitable for situations where you need to handle a large number of connections with less data interaction for each connection, and want to make full use of the multi-core performance of the CPU.

  • To summarize the applicable scenarios of various I/O models:
    BIO is suitable for situations where the number of connections is small and the data interaction of each connection is frequent, but it is not suitable for high concurrency environments.
    NIO is suitable for situations where a large number of connections need to be processed, but the data interaction of each connection is relatively small, and has better performance and resource utilization.
    AIO is suitable for situations where you need to handle a large number of connections with less data interaction for each connection, and you want to make full use of the multi-core performance of the CPU.
    Choosing the appropriate I/O model depends on the characteristics and needs of the application, and different models provide different performance and scalability.

Guess you like

Origin blog.csdn.net/qq_42785250/article/details/132973244