PrintWriter与Java中的FileWriter [英] PrintWriter vs FileWriter in Java

查看:114
本文介绍了PrintWriter与Java中的FileWriter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中的PrintWriter和FileWriter是否相同,无论使用哪一个?到目前为止,我使用了两者,因为他们的结果是一样的。是否有一些特殊情况下更喜欢一个而不是另一个?

Are PrintWriter and FileWriter in Java the same and no matter which one to use? So far I have used both because their results are the same. Is there some special cases where it makes sense to prefer one over the other?

public static void main(String[] args) {

    File fpw = new File("printwriter.txt");
    File fwp = new File("filewriter.txt");
    try {
        PrintWriter pw = new PrintWriter(fpw);
        FileWriter fw = new FileWriter(fwp);
        pw.write("printwriter text\r\n");
        fw.write("filewriter text\r\n");
        pw.close();
        fw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}


推荐答案

根据coderanch.com,如果我们合并得到的答案:

According to coderanch.com, if we combine the answers we get:

FileWriter是IO的字符表示。这意味着它可以用来写字符。在内部,FileWriter将使用底层操作系统的默认字符集,并将字符转换为字节并将其写入磁盘。

FileWriter is the character representation of IO. That means it can be used to write characters. Internally FileWriter would use the default character set of the underlying OS and convert the characters to bytes and write it to the disk.

PrintWriter& FileWriter。

PrintWriter & FileWriter.

相似之处


  1. 两者均来自Writer。

  2. 两者都是字符表示类,这意味着它们使用字符并使用默认字符集将它们转换为字节。

差异


  1. 如果IO出现任何故障,FileWriter会抛出IOException,这是一个经过检查的异常。

  2. 没有PrintWriter方法抛出IOException,而是设置了一个布尔标志,可以使用checkError()获得。

  3. PrintWriter在可选构造函数上有可用于在特定方法时启用自动刷新叫做。 FileWriter中不存在这样的选项。

  4. 当写入文件时,FileWriter有一个可选的构造函数,允许它在调用write()方法时附加到现有文件。 li>
  1. FileWriter throws IOException in case of any IO failure, this is a checked exception.
  2. None of the PrintWriter methods throws IOException , instead they set a boolean flag which can be obtained using checkError().
  3. PrintWriter has on optional constructor you may use to enable auto-flushing when specific methods are called. No such option exists in FileWriter.
  4. When writing to files, FileWriter has an optional constructor which allows it to append to the existing file when the "write()" method is called.

PrintStream和OutputStream之间的区别:类似于上面的解释,只需用byte替换字符。

Difference between PrintStream and OutputStream: Similar to above explanation, just replace character with byte.

PrintWriter有以下方法:

PrintWriter has following methods :

close()
flush()
format()
printf()
print()
println()
write()

和构造函数是:

File (as of Java 5)
String (as of Java 5)
OutputStream
Writer

而FileWriter有以下方法:

while FileWriter having following methods :

close()
flush()
write()

和构造函数是:

File
String 

链接: http://www.coderanch.com/t/418148/java-programmer -SCJP / certification / Information-PrintWriter-FileWriter

这篇关于PrintWriter与Java中的FileWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆