在Java中,可以使用java.util
包中的类来处理文件的输入输出(I/O)操作。以下是一些常用的方法和类:
java.util.Scanner
类读取文件内容:import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
File file = new File("path/to/your/file.txt");
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
java.util.BufferedReader
类读取文件内容:import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
File file = new File("path/to/your/file.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
java.util.PrintWriter
类写入文件内容:import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteFile {
public static void main(String[] args) {
File file = new File("path/to/your/outputfile.txt");
try (PrintWriter writer = new PrintWriter(file)) {
writer.println("Hello, World!");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
这些示例展示了如何使用Java的java.util
包中的类来读取和写入文件。注意,这些示例使用了try-with-resources语句,这是一种自动关闭资源(如文件)的现代方法,可以避免资源泄漏。