PrintWriter和FileWriter类之间的区别 [英] Difference between PrintWriter and FileWriter class
本文介绍了PrintWriter和FileWriter类之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试{
文件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。
$ 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.
这篇关于PrintWriter和FileWriter类之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文