java中如何读取文件
读取文件的方法
在Java中,读取文件可以通过多种方式实现,以下是几种常见的方法:
使用BufferedReader读取文本文件
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.readAllLines读取所有行
Java 8及以上版本可以使用Files.readAllLines一次性读取所有行:
try {
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用Scanner逐行读取
Scanner适合逐行读取文件内容:

try (Scanner scanner = new Scanner(new File("file.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
使用Files.readAllBytes读取二进制文件
对于二进制文件,可以使用Files.readAllBytes读取全部字节:
try {
byte[] bytes = Files.readAllBytes(Paths.get("file.bin"));
// 处理字节数据
} catch (IOException e) {
e.printStackTrace();
}
使用InputStream读取大文件
对于大文件,推荐使用InputStream分块读取以避免内存溢出:
try (InputStream is = new FileInputStream("largefile.bin")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
// 处理buffer中的数据
}
} catch (IOException e) {
e.printStackTrace();
}
注意事项
- 使用
try-with-resources语法可以自动关闭资源,避免内存泄漏。 - 处理文件路径时,建议使用
Paths.get()或File类构造绝对路径。 - 对于大文件,避免一次性读取全部内容,改用流式处理。
以上方法涵盖了从文本文件到二进制文件的读取需求,根据具体场景选择合适的方式即可。






