java 如何读取文件
读取文件的常用方法
Java提供了多种读取文件的方式,可以根据需求选择不同的类和方法。以下是几种常见的实现方式:
使用 FileReader 和 BufferedReader
这种方式适合逐行读取文本文件,效率较高:
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用 Files 类(Java 7+)
Java NIO提供的Files类提供了简洁的文件读取方法:
Path path = Paths.get("file.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.forEach(System.out::println);
使用 Scanner 类
适合需要解析文件内容的场景:
try (Scanner scanner = new Scanner(new File("file.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
使用 FileInputStream 读取二进制文件
适合读取非文本文件:
try (FileInputStream fis = new FileInputStream("file.bin")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
// 处理二进制数据
}
} catch (IOException e) {
e.printStackTrace();
}
注意事项
- 处理文件路径时,建议使用
Paths.get()或new File()的绝对路径 - 所有I/O操作都应该在try-with-resources语句中执行,确保资源自动关闭
- 大文件读取应考虑使用缓冲或分块读取,避免内存溢出
- 注意处理各种可能的IO异常
选择哪种方法取决于具体需求,如文件大小、内容类型和处理方式等因素。对于简单文本文件,Files.readAllLines()最为简洁;需要逐行处理时BufferedReader更合适;二进制文件则必须使用字节流。







