java如何读写文件
读取文件
使用 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();
}
对于二进制文件,可以使用 FileInputStream 配合 BufferedInputStream 提高读取效率。通过字节数组缓存数据,适用于非文本文件。
try (FileInputStream fis = new FileInputStream("file.bin");
BufferedInputStream bis = new BufferedInputStream(fis)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
// 处理读取到的字节数据
}
} catch (IOException e) {
e.printStackTrace();
}
写入文件
使用 BufferedWriter 写入文本文件时,可以调用 write() 方法写入字符串,newLine() 方法添加换行符。需要显式调用 flush() 或关闭流确保数据写入磁盘。
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("Hello, World!");
bw.newLine();
bw.write("Another line");
} catch (IOException e) {
e.printStackTrace();
}
对于二进制文件写入,FileOutputStream 配合 BufferedOutputStream 是常见选择。通过字节数组批量写入数据,适合处理图片、音频等二进制内容。
try (FileOutputStream fos = new FileOutputStream("output.bin");
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
byte[] data = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // Hello的ASCII码
bos.write(data);
} catch (IOException e) {
e.printStackTrace();
}
NIO文件操作
Java NIO提供了更现代的API,Files 类包含便捷方法。读取所有行到列表只需一行代码,适合小文件处理。
try {
List<String> lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
NIO写入文件同样简洁,可以指定打开选项。StandardOpenOption.CREATE 会在文件不存在时创建,APPEND 实现追加写入。
try {
Files.write(Paths.get("output.txt"),
"New content".getBytes(),
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
异常处理
无论使用哪种方式,都必须妥善处理 IOException。try-with-resources 语法能自动关闭资源,避免忘记调用 close() 方法导致资源泄漏。
对于文件路径处理,推荐使用 Paths.get() 替代硬编码路径,增强跨平台兼容性。字符编码建议显式指定为 StandardCharsets.UTF_8,避免平台默认编码差异问题。







