java如何抓取文件
使用 FileInputStream 读取文件
通过 FileInputStream 逐字节读取文件内容,适合处理二进制文件或小文件。
try (FileInputStream fis = new FileInputStream("path/to/file")) {
int content;
while ((content = fis.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
使用 BufferedReader 逐行读取文本文件
BufferedReader 配合 FileReader 实现高效文本行读取,适合处理大文本文件。
try (BufferedReader br = new BufferedReader(new FileReader("path/to/file"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用 Files.readAllBytes 快速读取小文件
Java 7+ 的 Files 类提供一次性读取全部字节的方法,适用于已知大小的文件。
Path path = Paths.get("path/to/file");
byte[] fileContent = Files.readAllBytes(path);
String textContent = new String(fileContent, StandardCharsets.UTF_8);
使用 Files.readAllLines 读取文本行列表
直接获取文本文件所有行作为 List<String>,注意内存限制。
List<String> lines = Files.readAllLines(Paths.get("path/to/file"));
lines.forEach(System.out::println);
使用 Scanner 类解析文件
适合需要按特定分隔符处理文本的场景,支持正则表达式匹配。

try (Scanner scanner = new Scanner(new File("path/to/file"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
注意事项
- 文件路径可使用绝对路径或相对路径(相对于项目根目录)
- 所有方法均需处理
IOException - 大文件建议使用流式读取(前两种方法)
- 字符编码需与文件实际编码一致(默认UTF-8)






