This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
explain
What is IO? I (Input), where the CPU reads data from the outside. O (Output) : outputs data from the CPU to external devices.
IO classification
- By function/flow:
Input streams: Only read data, but not write data. Streams based on InputStream/Reader belong to input streams.
Output streams: Data can be written but not read. Streams based on OutputStream/Writer belong to output streams.
- Divided by processing unit:
Byte stream: Reads and writes bytes in bytes, so garbled characters may occur. The base class is InputStream/OutputStream. The byte stream has no buffer and is output directly.
Character stream: Reads and writes characters character by character or line by line. The base class is Reader/Writer. Character streams are preferred for text processing and byte streams are used for other data types. The character stream uses a buffer, so the message is printed only when the close() method is called to close the buffer. To print the message when the character stream is not closed, you need to call flush().
- By role:
Node flow (low-level flow) : Reads and writes data directly from external devices.
Processing stream (advanced stream) : Processing an existing stream, not a separate stream, e.g. BufferedInputStream.
Flow switch
Byte streams and character streams are interchangeable.
- OutputStreamWriter can turn character streams into byte streams.
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(
new File("file")), "UTF-8");
Copy the code
- InputStreamReader converts a byte stream into a character stream.
InputStreamReader inr = new InputStreamReader(
new FileInputStream(
new File("file")), "UTF-8");
Copy the code
IO Usage Summary
IO’s API is cumbersome, but well designed, so it’s easy to choose the right ONE for your needs. First, you can choose to use character stream or byte stream according to whether the IO of the operation is used to process text. Then, you can choose the direction according to whether the current operation is read or write. Finally, you can choose the specific implementation class according to the type of operation, such as: reading files can use FileReader.