try{
File file = new File("write.txt");
FileWriter writer = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println("pqr");
printWriter.println("jkl");
printWriter.close();
PrintWriter printWriter = new PrintWriter(file);
printWriter.println("abc");
printWriter.println("xyz");
printWriter.close();
}
我不明白这两种方式有什么区别。 在哪种情况下我应该使用 printWriter 和 fileWriter。
虽然这两个内部都使用 FileOutputStream ,但主要区别在于 PrintWriter 提供了一些附加的格式化方法,如 println 和 printf。
代码片段:
public PrintWriter(File file) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
}
public FileWriter(File file) throws IOException {
super(new FileOutputStream(file));
}
主要差异:
从源头来看,当您传递文件时,PrintWriter 所做的是以缓冲方式打开它
public PrintWriter(File file) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
}
如果你传递给它一个 FileWriter,它会打开它,没有缓冲
public FileWriter(File file) throws IOException {
super(new FileOutputStream(file));
}
这意味着第一个示例可以稍微更高效。不过,我会使用
File
而不使用 FileWriter
,因为对我来说它更简单。
PrintWriter
为您提供了一些方便的格式化方法,例如 println
和 printf
。因此,如果您需要编写打印文本 - 您可以使用它。 FileWriter
更像是“低级”编写器,使您能够仅编写字符串和字符数组。基本上我认为你的选择没有太大区别。
虽然 FileWriter 只有一组基本方法,但 PrintWriter 拥有一组丰富的便捷方法,其中之一就在您的示例中 -
PrintWriter.println
。
您还应该记住“此类中的方法永远不会抛出 I/O 异常,尽管它的某些构造函数可能会抛出 I/O 异常。客户端可以通过调用 checkError() 来查询是否发生了任何错误”
两者之间最重要的区别之一是,使用 FileWriter 您可以将文本附加到现有文件的末尾,而使用 PrintWriter 则不能。
以下是它们之间的一些区别:
自动刷新:
PrintWriter
有一个选项,每当写入操作完成时自动刷新。 FileWriter
没有此功能。
不同数据类型的方法:
PrintWriter
有打印不同类型数据的方法,如整数、浮点数、字符串、对象等。FileWriter
是一个字符输出流,将文本写入字符文件。它更基本,只有写入字符或字符串的方法。
错误处理:
PrintWriter
抑制IOExceptions
。使用 IOException
时不会得到 PrintWriter
,除非您使用 checkError()
显式检查它。另一方面, FileWriter
会抛出 IOException
,您需要处理它。
性能:
PrintWriter
可能比FileWriter
慢,因为它需要解析不同类型的数据。
一般来说,当你需要向文件写入不同类型的数据或使用其内置方法时,
PrintWriter
使用起来更方便,而FileWriter
是用于向文件写入字符的更基础的类。