Java IO stream - [Build an information management system from scratch]

Java I/O Stream - [Building an Information Management System from Scratch]


What is Java I/O stream

introduce

Java's IO stream (Input/Output Stream) is a mechanism for reading and writing data. IO streams provide a unified way to handle different types of input and output, including

Including files, network connections, memory buffers, etc.

In Java, the IO stream is divided into input stream (InputStream) and output stream (OutputStream) according to the flow direction of the data. Input streams are used to read from data sources (e.g. files, network connections)

While reading data from an output stream, an output stream is used to write data to a destination (e.g. a file, a network connection). This streaming approach enables transparent access to different types of data sources without

Heart bottom implementation details.

Java provides many different types of IO streams to meet the needs of different scenarios. Common IO streams include ByteStream and CharacterStream. Character

Throttle reads and writes in bytes, mainly using subclasses of InputStream and OutputStream, such as FileInputStream and FileOutputStream. character stream with

Read and write in units of characters, mainly using subclasses of Reader and Writer, such as FileReader and FileWriter. Character stream is more convenient when processing text data, you can directly

Directly handle Unicode characters.

In addition, Java also provides a buffered stream (Buffered Stream), which encapsulates the underlying input stream or output stream, and provides a buffer in memory, which can improve the performance of IO.

performance. Buffered streams are often used with other types of streams, such as BufferedInputStream and BufferedOutputStream.

In addition to byte streams and character streams, Java also provides object streams (Object Stream) for serializing and deserializing Java objects. Object streams can convert Java objects to byte order

column, and then saved to a file or sent to the network, it is also possible to restore the sequence of bytes to a Java object. Object streams are implemented using ObjectInputStream and ObjectOutputStream

now.

In short, Java's IO stream is a powerful and flexible tool that can easily read and write data. It provides a unified interface that abstracts different types of data sources

The details allow developers to focus more on business logic without paying too much attention to the underlying IO operations.

understand

IO streams can be used when we need to read or write data in Java. You can think of an IO stream as a pipeline where data flows from one place to another.

There are two types of IO streams: input streams and output streams. Input streams are used to read data from a data source (such as a file or network), while output streams are used to write data to a destination (such as a file or network

network).

There are two basic streams in the IO stream: byte stream and character stream. Byte streams deal with raw data (such as pictures or audio), while character streams deal with text data. Character flow is more square

Handle text easily because they can handle Unicode characters directly.

To improve performance, we can also use buffered streams. They are equivalent to placing a buffer at both ends of the stream, which can read or write multiple data at a time, which can improve efficiency.

Also, if we want to save objects or send them to the network, we can use object streams. Object streams can convert Java objects into sequences of bytes and can reverse this process

process, from a sequence of bytes to a Java object.

In general, Java's IO stream is a tool for processing input and output, which can help us read and write data. It provides different types of streams to handle different types of data

data, and can improve performance and handle complex operations by buffering streams and object streams. Using IO streams allows us to more easily process data without paying too much attention to low-level details.

The difference between byte stream and character stream

The byte stream reads a single byte, and the character stream reads a single character (a character depends on the encoding, and the corresponding byte is also different, such as UTF-8 encoding is 3 bytes, Chinese encoding is 2

bytes. ) byte stream is used to process binary files (pictures, MP3, video files), and character stream is used to process text files (it can be regarded as a special binary file, using a certain

code, human readable).

In short, bytes are for computers, and characters are for humans.

The role of Java I/O streams

Java's IO stream is mainly used to read and write data. It provides a convenient and uniform way to handle different types of input and output, including files, network, memory, etc.

Specifically, Java's IO streams can be used to:

  • Read data from or write data to a file.
  • Data input and output are performed via a network connection.
  • Create buffers in memory to temporarily store data.
  • Handle text data, reading and writing in units of characters.
  • Handles binary data, reading and writing bytes.

Using Java's IO streams, you can easily read the contents of files, write data to files, communicate with programs on other computers, process the contents of text files, and transfer data between different data sources.

Java's IO streams are a useful tool for handling input and output, which makes it easy to read and write different types of data without having to care deeply about the underlying details.

Java I/O stream methods

InputStream method

Reader method

OutputStream method

Writer method

All classes of the Java I/O system

Example of use

In Java, reading and writing data using I/O streams involves the following basic steps:

  1. Opening a stream: First, you need to create a corresponding stream object to represent the input or output data source. For example, use FileInputStreamto read a file and use FileOutputStreamto write a file.
  2. Read or write data: call the corresponding method through the stream object to actually read or write data. For example, for a byte stream, you can use read()a method to read a byte and write()a method to write a byte; for a character stream, you can use read()a method to read a character and a write()method to write a character.
  3. Close the stream: After the data is read or written, the stream should be closed in time to release related resources. The stream can be closed using close()the method.

Example:

import java.io.*;

public class IOExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 1. 使用字节流读取文件
            FileInputStream fis = new FileInputStream("input.txt");
            int data;

            while ((data = fis.read()) != -1) {
    
    
                // 处理读取到的字节数据
                System.out.print((char) data);
            }

            fis.close(); // 关闭流

            // 2. 使用字符流写入文件
            FileWriter fw = new FileWriter("output.txt");
            String content = "Hello, World!";

            fw.write(content); // 写入数据

            fw.close(); // 关闭流
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

In the above example, first create a FileInputStreamfile to read, and use read()the method to read the file content byte by byte. Then, created a

FileWriterto write to a file and use write()the method to write a string to a file.

It should be noted that during the process of reading or writing data, exceptions may occur IOException, so exceptions need to be handled appropriately.

It is necessary to select the appropriate stream type according to the specific data source and requirements, and follow the basic operation steps of opening, reading/writing, and closing the stream to use Java's I/O stream.

The effect of using Java I/O streams in practical applications

  1. Data reading and writing: through Java's I/O stream, you can easily read and write data in files. This makes manipulating files, such as reading text content, copying files, writing configuration files, etc. easy.
  2. Network communication: Java's I/O stream provides classes such as Socket and ServerSocket, which can be used for network communication. Through the network I/O flow, the communication between the client and the server can be easily established for data transmission and message interaction.
  3. Memory buffering: Buffered streams in Java's I/O streams (such as BufferedReader and BufferedWriter) can improve I/O performance. The use of buffered streams can reduce frequent read and write operations on the underlying data source. By creating buffers in memory, data can be processed in batches to speed up data reading and writing.
  4. Object serialization: Java's I/O stream provides object streams (ObjectInputStream and ObjectOutputStream) for serialization and deserialization of objects. This makes it possible to convert Java objects into byte streams for storage or transmission, and restore byte streams to Java objects, which plays an important role in distributed systems and data persistence.
  5. Processing text data: Java's character streams (Reader and Writer) are mainly used to process text data, support specified character sets, and provide character encoding and decoding functions. Character streams can easily read and write text files, and perform string operations, such as reading data in CSV, XML, or JSON formats.

Overall, Java's I/O streams provide developers with a range of tools for reading and writing data. They help simplify the processing of different types of data and improve application

To work.
5. Processing text data: Java's character streams (Reader and Writer) are mainly used to process text data, support specified character sets, and provide character encoding and decoding functions. Character streams can easily read and write text files, and perform string operations, such as reading data in CSV, XML, or JSON formats.

Overall, Java's I/O streams provide developers with a range of tools for reading and writing data. They help simplify the processing of different types of data and improve application

flexibility, scalability and efficiency. Whether it is processing files, network communications, data buffering, or object serialization, Java's I/O streams play an important role.

Guess you like

Origin blog.csdn.net/m0_73879806/article/details/132262396