更新时间:2023-12-04 12:26:28
尽管这两个内部使用FileOutputStream,不同之处在于PrintWriter提供了一些额外的格式化方法,如println和printf。
$ b $ p
代码片段:
public PrintWriter(File file)引发FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
$ b public FileWriter(File file)throws IOException {
super(new FileOutputStream(file));
$ b $ p
$ b 主要区别: ol>
如果发生任何IO故障,FileWriter将抛出IOException。
没有一个PrintWriter方法抛出IOException,而是设置了一个布尔标志,可以使用checkError ()。
写入数据的每个字节后,PrintWriter会自动调用flush。在FileWriter的情况下,调用者必须照顾调用flush。
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();
}
I don't understand what is difference bet'n these two way.
In which scenario i should use printWriter and fileWriter.
Although both of these internally uses a FileOutputStream , the main difference is that PrintWriter offers some additional methods for formatting like println and printf.
code snippets:
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));
}
Major Differences :
- FileWriter throws IOException in case of any IO failure.
- None of the PrintWriter methods throws IOException, instead they set a boolean flag which can be obtained using checkError().
- PrintWriter automatically invokes flush after every byte of data is written. In case of FileWriter, caller has to take care of invoking flush.