java中如何打开文件
使用 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();
}
使用 FileReader 打开文件(字符流)
专为文本文件设计,直接以字符形式读取内容,避免字节到字符的转换问题。适合处理纯文本文件如 .txt、.csv。

try (FileReader reader = new FileReader("path/to/file")) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character); // 处理字符数据
}
} catch (IOException e) {
e.printStackTrace();
}
使用 BufferedReader 提高读取效率
包装 FileReader 或 InputStreamReader,通过缓冲区减少IO操作次数。适合逐行读取大文本文件。

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 类(Java NIO)
Java 7+ 引入的NIO.2 API,提供更简洁的文件操作方法。Files.readAllLines() 适合快速读取小文件。
Path path = Paths.get("path/to/file");
try {
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.forEach(System.out::println); // 处理所有行
} catch (IOException e) {
e.printStackTrace();
}
使用 Scanner 解析文件内容
结合正则表达式解析结构化文本,适合按特定模式(如分隔符)读取文件。
try (Scanner scanner = new Scanner(new File("path/to/file"))) {
scanner.useDelimiter(","); // 设置分隔符
while (scanner.hasNext()) {
System.out.println(scanner.next()); // 按分隔符读取
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
注意事项
- 文件路径可以是绝对路径(如
C:/data/file.txt)或相对路径(相对于项目根目录)。 - 使用
try-with-resources语法确保流自动关闭,避免资源泄漏。 - 处理大文件时优先使用
BufferedReader或分块读取(NIO的Files.lines()),避免内存溢出。 - 指定字符编码(如
StandardCharsets.UTF_8)防止乱码问题。






