java 如何读取文件
读取文件的方法
在Java中,读取文件可以通过多种方式实现,以下是几种常见的方法:
使用 FileReader 和 BufferedReader
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+)
Files 类提供了便捷的方法来读取文件的所有行或字节。
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();
}
使用 InputStream 和 FileInputStream
适用于读取二进制文件或字节流。
try (InputStream is = new FileInputStream("file.txt")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
使用 Files.newBufferedReader(Java 8+)
结合 Path 和 Charset 来读取文件,支持指定字符编码。
try (BufferedReader reader = Files.newBufferedReader(Paths.get("file.txt"), StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
注意事项
- 文件路径可以是相对路径或绝对路径,需确保文件存在且可读。
- 使用
try-with-resources语法可以自动关闭资源,避免内存泄漏。 - 处理
IOException是必要的,以应对文件不存在或读取失败的情况。 - 对于大文件,建议使用缓冲或逐行读取,避免内存溢出。







