Java I/O streams provide classes and interfaces for handling file system operations. Among them, the file stream is divided into input stream and output stream, which are used to read and write file content respectively. In addition, Java I/O also provides classes for directory operations, such as File, FileFilter and FileNameFilter, which can obtain file lists, create or delete directories, etc.
Java I/O Streams: Detailed explanation of file system operations
Introduction
Java I/O streams provide a set of classes and interfaces for handling file system operations. By using I/O streams, you can read, write, and manipulate files in the file system in a Java program.
File Stream
1. Input stream
FileInputStream
: Read from file Get the byte sequence. FileReader
: Read character sequence from file. 2. Output stream
FileOutputStream
: Write a byte sequence to the file. FileWriter
: Write a sequence of characters to the file. Example: Reading file contents
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FileInputStreamExample { public static void main(String[] args) { try { // 创建文件输入流对象 FileInputStream fis = new FileInputStream(new File("file.txt")); // 创建字节数组以存储文件内容 byte[] data = new byte[fis.available()]; // 读取文件内容并存储在字节数组中 int bytesRead = fis.read(data); // 将字节数组转换为字符串并打印 String fileContent = new String(data, 0, bytesRead); System.out.println(fileContent); // 关闭文件输入流 fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
Directory operations
In addition to file streams, Java I /O also provides some classes for directory operations:
File
: Represents a single file or directory. FileFilter
: used to filter files. FileNameFilter
: Used to filter the names of files and directories. Example: Get the file list in the directory
import java.io.File; import java.util.Arrays; public class FileListExample { public static void main(String[] args) { // 创建 File 对象代表当前目录 File dir = new File("."); // 获取当前目录下的文件列表 File[] files = dir.listFiles(); // 打印文件列表 Arrays.stream(files).forEach(System.out::println); } }
The above is the detailed content of How do Java I/O streams handle file system operations?. For more information, please follow other related articles on the PHP Chinese website!