This article takes you to understand Java's IO mechanism

One: Story Background

Recently, I am reviewing the I/O mechanism of Java. I have done the corresponding file upload work through the I/O operation of Java before. Docked with other three-party platforms and uploaded files through streaming. But there has been no systematic summary, Java streams and Java stream operations. Today, I will summarize Java's I/O operations here, introduce the concept of streams, and commonly used APIs.

Two: What is Java's I\O mechanism

Before talking about Java I/O, let us clarify a few concepts:

2.1 stream

  • I/O operations in Java are mainly performed through streams.
  • A stream is an abstraction over a sequence of bytes used to read data from an input source (input) or write data to an input destination (output).
  • Streams in Java are divided into two categories: byte streams (InputStream and OutputStream), character streams (Reader and Writer), and these two categories can be divided into input streams (InputStream, Reader) and output streams (OutputStream, Writer) according to their functions.

2.1.2 The difference between byte stream and character stream

The main differences between character streams and byte streams are as follows:

  1. data unit
    • Byte stream reads and writes in bytes
    • The character stream reads and writes in units of characters (char)
  2. processing content
    • Byte streams are suitable for handling binary data. (eg: image, audio, video)
    • Character streams are suitable for handling text data. (processed in units of characters)
  3. underlying implementation
    • The bottom layer of the byte stream uses byte sequences to read and write, and usually directly manipulates the underlying byte stream (file stream, network stream)
    • Character streams read and write through character sequences , usually based on byte streams, and use encoding (such as: utf-8) to convert characters into bytes.
  4. Cushioning performance
    • Byte stream passing (BufferedInputStream and BufferedOutputStream) to improve I/O performance
    • Character stream passing (BufferedReader and BufferedWriter) to improve I/O performance

2.1.3 The difference between input stream and output stream

  • Input Stream (InputStream, Reader): Used to read data from sources, such as reading data from files, network connections, standard input streams (keyboard input).
  • The output stream (OutputStream/Writer) is used to write data to the target, such as writing data to a file, network connection or standard output stream (screen output).

2.2 Document I/O

  • Java provides the File class and FileInputStream/FileOutputStream class for reading and writing files.
  • You can use FileInputStream to open a file and read data in it, and FileOutputStream to create a file and write data.

2.3 Crash I/O

  • Java provides buffered streams (BufferedInputStream/BufferedOutputStream and BufferedReader/BufferedWriter) to improve I/O performance.
  • Buffered streams improve efficiency by buffering data in memory, reducing the actual read and write operations to the physical device each time.

2.4 Standard Input/Output

There are three types of standard streams in Java:

  • System.out standard output stream
  • System.in standard input stream
  • System.err standard error stream

2.5 Object serialization and deserialization

  • Java's object serialization mechanism allows objects to be converted to a stream of bytes for transmission over the network or storage to a file.
  • You can use ObjectInputStream and ObjectOutputStream to read and write serialized objects.

2.6 NI/O

  • Java NIO is a higher-level I/O API introduced in Java 1.4.
  • NIO provides non-blocking I/O operations and high-performance I/O processing methods, which are suitable for scenarios that handle a large number of concurrent connections.
  • NIO uses channels (Channel) and buffers (Buffer) for data read and write operations, and event-driven multiplexing through Selector.

Three: Draw a picture to represent the Java I/O mechanism

3.1 Flowchart of input input system

This diagram represents an entire process with given input and output:
insert image description here

3.2 Input stream

We mentioned above that streams in Java are mainly divided into byte streams and character streams. Here we mainly give a schematic diagram of byte streams and character streams.

Byte input stream:
insert image description here
character input stream:
insert image description here

3.3 Output stream

Character input stream:

insert image description here
Character output stream:
insert image description here

Four: Java I/O common API

4.1 FileInputStream和FileOutputStream

FileInputStream and FileOutputStream are commonly used file processing classes, which can be used for file input and output operations.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileIOExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 文件输入流
            FileInputStream input = new FileInputStream("input.txt");
            // 文件输出流
            FileOutputStream output = new FileOutputStream("output.txt");
            
            // 读取文件并写入到另一个文件
            int data;
            while ((data = input.read()) != -1) {
    
    
                output.write(data);
            }
            
            // 关闭流
            input.close();
            output.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

4.2 BufferedReader和BufferedWriter

BufferedReader and BufferedWriter (for buffered text input and output):

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedIOExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 读取文件
            BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
            // 写入文件
            BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
            
            // 逐行读取并写入到另一个文件
            String line;
            while ((line = reader.readLine()) != null) {
    
    
                writer.write(line);
                writer.newLine(); // 写入换行符
            }
            
            // 关闭流
            reader.close();
            writer.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

4.3 Socket and ServerSocket:

For socket communication in network programming:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 创建服务器套接字并监听指定端口
            ServerSocket serverSocket = new ServerSocket(8080);
            System.out.println("Server started. Waiting for client connection...");
            
            // 等待客户端连接
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected.");
            
            // 获取输入流和输出流
            InputStream input = clientSocket.getInputStream();
            OutputStream output = clientSocket.getOutputStream();
            
            // 读取客户端发送的数据
            byte[] buffer = new byte[1024];
            int bytesRead = input.read(buffer);
            String data = new String(buffer, 0, bytesRead);
            System.out.println("Received data from client: " + data);
            
            // 向客户端发送响应数据
            String response = "Hello from server!";
            output.write(response.getBytes());
            
            // 关闭流和套接字
            input.close();
            output.close();
            clientSocket.close();
            serverSocket.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

Five: Summary

This article gives specific concepts and examples of I/O and N/IO. If you are interested, you can copy the code locally, run it, and try to run it. Through debugging, understand the use of java I/O.

Guess you like

Origin blog.csdn.net/hlzdbk/article/details/131320800