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();
}
使用 Scanner
适合按分隔符(如空格、换行)读取数据,灵活性高。
try (Scanner scanner = new Scanner(new File("file.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
使用 Files.readAllLines()(Java 7+)
一次性读取所有行到列表,适合小文件。
try {
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
使用 Files.lines()(Java 8+)
通过流式处理逐行读取,适合大文件。
try (Stream<String> stream = Files.lines(Paths.get("file.txt"))) {
stream.forEach(System.out::println);
} catch (IOException 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()或绝对路径避免路径错误。 - 资源管理:务必使用
try-with-resources确保流自动关闭。 - 大文件处理:避免
readAllLines()直接加载大文件,优先选择流式处理。







