What is the usage method of the Java stream?
Streams in Java are an abstract mechanism used to handle input and output operations. They allow for transferring data from one location to another, such as reading data from a file into a program or outputting data from a program to a file.
Streams can be classified into input streams and output streams. Input streams are used to read data from external data sources, while output streams are used to write data to external data sources. Stream operations in Java are mainly implemented through classes in the java.io package.
The basic steps of using Java streams are as follows:
- Create stream objects: Create objects for input streams or output streams as needed.
- Connect to a data source: establish a connection to access data that needs to be read or written, such as files, network connections, etc.
- Read or write data: use the methods of stream objects to read or write data.
- Close the stream: It is important to promptly close the stream after using it to release resources.
The sample code is shown below:
import java.io.*;
public class StreamExample {
public static void main(String[] args) throws IOException {
// 创建文件输出流
FileOutputStream fos = new FileOutputStream("output.txt");
// 写入数据到文件中
String data = "Hello, Java Stream!";
fos.write(data.getBytes());
// 关闭流
fos.close();
// 创建文件输入流
FileInputStream fis = new FileInputStream("output.txt");
// 读取文件中的数据
int ch;
while ((ch = fis.read()) != -1) {
System.out.print((char)ch);
}
// 关闭流
fis.close();
}
}
The above code demonstrates how to write and read files using Java streams. By using streams, various I/O operations, including file operations, network operations, etc., can be easily carried out. Java also provides some advanced streams, such as buffered streams, object streams, data streams, etc., which can further simplify stream operations.