PrintWriter适合格式化输出,提供print/println/printf方法,自动处理异常但需手动检查错误;BufferedWriter带缓冲提升写入性能,配合newLine()跨平台换行,适合大量文本写入;两者均推荐使用try-with-resources确保资源释放。

Java中使用PrintWriter和BufferedWriter写文件都很常见,它们各有特点,适用于不同场景。下面分别介绍如何用这两个类写入文件,并说明关键区别和使用建议。
PrintWriter 提供了更方便的打印方法,比如 print()、println()、printf(),适合输出格式化文本。它会自动处理异常(不会抛出IOException,但需要手动检查错误状态)。
示例:使用 PrintWriter 写入文件
import java.io.PrintWriter;
import java.io.IOException;
public class WriteWithPrintWriter {
public static void main(String[] args) {
try (PrintWriter pw = new PrintWriter("output1.txt")) {
pw.println("第一行内容");
pw.println("第二行内容");
pw.printf("年龄:%d,姓名:%s%n", 25, "张三");
} catch (IOException e) {
System.err.println("写入失败:" + e.getMessage());
}
}
}
注意:PrintWriter 默认不会自动刷新,若需立即写入,可使用 new PrintWriter(file, true) 启用自动刷新(仅对 println 等方法有效)。
立即学习“Java免费学习笔记(深入)”;
BufferedWriter 是带缓冲的字符流,能显著提升写入性能,尤其在频繁写小段数据时。它本身没有格式化功能,但可以配合 String.format() 使用。
示例:使用 BufferedWriter 写入文件
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteWithBufferedWriter {
public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output2.txt"))) {
bw.write("第一行内容");
bw.newLine(); // 换行
bw.write("第二行内容");
bw.newLine();
bw.write(String.format("年龄:%d,姓名:%s", 25, "张三"));
} catch (IOException e) {
System.err.println("写入失败:" + e.getMessage());
}
}
}
newLine() 方法会根据操作系统自动添加换行符(如 Windows 是 \r\n,Linux 是 \n)。
checkError() 判断是否出错。基本上就这些。两种方式都能高效写文件,按需求选合适的一种即可。不复杂但容易忽略的是资源释放和换行处理。
以上就是Java PrintWriter和BufferedWriter如何写文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号