Java IO flow (practical operation)


In Java, IO stream is a mechanism for handling input and output operations. It provides a unified way to read and write data. In daily development, IO streams are frequently used in file reading and writing, network communication, database operations in specific scenarios, text processing, etc.

The main functions of streams are input and output. The simplest understanding:

Obtaining the content in the txt text and processing it in the program is called the input stream (Input), and writing the content processed by the program into the txt text is called the output stream (Output). To put it bluntly, one is responsible for reading and the other is responsible for writing.

1 IO flow principle

IO stream is based on the concept of stream, which treats the input and output of data as a continuous stream. Data flows from one place to another, and the direction of the flow can be input (reading data) or output (writing data). The IO stream in Java is divided into two types: byte stream and character stream, which are used to process byte data and character data respectively.

The principle of IO stream is to transmit data from source to destination through stream pipeline. The source can be a file, network connection, memory, etc., and the destination can be a file, database, network, etc. IO streams provide a rich set of classes and methods to implement different types of input and output operations.

2 Classification of IO streams

IO streams in Java can be classified according to the type of data and the direction of the stream.

  1. Classified by data type
    • Byte Stream: Read and write data in bytes, suitable for processing binary data, such as images, audio, video, etc. Common byte stream classes include InputStreamand OutputStream.
    • Character Stream (Character Stream): Read and write data in character units, suitable for processing text data. The character stream automatically encodes and decodes characters and can handle characters in multiple languages. Common character stream classes include Readerand Writer.
  2. Classification by direction of flow
    • Input Stream: used to read data. Input streams read data from data sources such as files, network connections, etc. Common input stream classes include FileInputStream, ByteArrayInputStream, SocketInputStream, etc.
    • Output Stream: used to write data. The output stream writes data to a destination , such as a file, database, network, etc. Common output stream classes include FileOutputStream, ByteArrayOutputStream, SocketOutputStream, etc.

The classification inheritance structure diagram is as follows:
Insert image description here

3 Input and output stream code examples

The two classes that are more commonly used in the development process are ` InputStreamand ` OutputStream. The higher-level parent classes of these two classes are abstract classes, and subclasses under them are usually created.

  • InputStream

    ByteArrayInputStream, StringBufferInputStream, FileInputStreamare three basic media streams, which read data from Byte array, StringBuffer, and local file respectively. Let's take FileInputStreamand FileOutputStreamas an example.

  • OutputStream

    ByteArrayOutputStream, FileOutputStreamare two basic media streams, which write data to Byte arrays and local files respectively. PipedOutputStream writes data to a pipe shared with other threads.

  1. FileInputStream case

    The steps for byte input stream are as follows:

    1. Create stream object
    2. Create a container array of buffered bytes
    3. Read data
    4. Manipulate arrays that hold data
    5. close stream
    public void input() throws IOException {
          
          
            String fileName="D:\\file\\测试.txt";
            File file = new File(fileName);
            InputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            //Reads some number of bytes from the input stream and stores them into the buffer array b.
            in.read(b);
            in.close();
            System.out.println(new String(b));
    }
    

    After converting the file into a stream, call read()the method to read the stream and save it into a byte array. The stored byte array is passed in as a parameter. You can see that what is printed is exactly what is written in the file.
    Insert image description here

  2. FileOutputStream case

    The steps to write an output stream to a file are as follows:

    1. Select a stream: Create a stream object
    2. Prepare the data source and convert the data source into a byte array type
    3. Write data to the file via stream
    4. refresh stream
    5. close stream
    public void output() throws IOException {
          
          
            String s = "hello";
            OutputStream out = new FileOutputStream("D:\\file\\输出.txt");
            byte[] bytes = s.getBytes();
            out.write(bytes);
            out.close();
        }
    

Insert image description here

OutputStream is a byte stream, so the output content must be converted into a byte array first, and then written out through the write(byte []) method.

Don't confuse the functions of InputStream/OutputStream and File

The first two are only responsible for reading and writing data into the file, and only perform diversified operations on the data content in the form of a stream. As for file generation, naming, and a series of operations related to the entire file, it is Filethe responsibility of the class.

The more commonly used one is BufferInputStreambuffered stream

Benefits of buffered streams:

The buffer stream contains a buffer area, the default is 8kb. Every time the program calls the read method, the content is actually read from the buffer area. If the read fails, it means that there is no content in the buffer area, then the content is read from the data source. Then it will read as many bytes as possible and put them into the buffer area. Finally, all the contents of the buffer area will be returned to the program. Reading data from the buffer is faster, more efficient, and has better performance than reading data directly from the data source.

simply say:

If there is no cache area, then each read will send an IO operation;
if there is a cache area, the first read will read x bytes and put them into the cache area, and then subsequent reads will read from the cache. When the read reaches the end of the buffer area, x bytes will be read again and put into the buffer area.

The methods for processing stream processing data and node streaming data are basically the same.

4 Summary

Reading and writing streams is actually very simple, and the steps are relatively fixed, but after converting the file into a stream, the operability becomes very large.

It is impossible to modify the file directly, but the stream is universal. If you change the content and form of the stream and then output it to the file, the displayed effect will change;

Second, the file may be very large. It is impossible to transmit such a large file on the network. It must be converted into a stream and transmitted continuously bit by bit. This is why you can pause and start at will during the download or upload process without any impact, because you just need to ensure that these bits and pieces are finally put together to be complete.

This article only demonstrates the simplest way of reading and writing data in txt text format. The principle is the same. Each bit of data has a unique corresponding bytecode, which can be converted from data to bytes and from bytes to data. That's why it's called a byte stream.

However, there are various file formats, and they must be converted into streams of the same format before output, that is, custom operations according to your own needs between InputStreamand operations.OutputStream

5 Files are transferred between the front and backend

During the development process, it is often necessary to transfer files from the front desk to the background or from the background to the front desk. How to achieve this step?
You can refer to this article, which includes an explanation of the upload and download process: https://blog.csdn.net/qq_43331014/article/details/132527328

Guess you like

Origin blog.csdn.net/qq_43331014/article/details/132525017