Java 中的 PrintWriter 与 FileWriter

发布于 2024-11-02 15:53:19 字数 601 浏览 6 评论 0 原文

Java中的PrintWriter和FileWriter是否相同,无论使用哪一个?到目前为止,我已经使用了这两种方法,因为它们的结果是相同的。在某些特殊情况下,是否有必要选择其中一种而不是另一种?

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();
    }

}

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();
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

小巷里的女流氓 2024-11-09 15:53:19

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

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

打印作家和文件编写器。

相似之处

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

差异

  1. FileWriter 在任何 IO 失败的情况下都会抛出 IOException,这是一个受检查的异常。
  2. 所有 PrintWriter 方法都不会抛出 IOException,而是设置一个布尔标志,可以使用 checkError() 获取该标志。
  3. PrintWriter 有一个可选的构造函数,您可以使用它在调用特定方法时启用自动刷新。 FileWriter 中不存在这样的选项。
  4. 写入文件时,FileWriter 有一个可选的构造函数,允许在调用“write()”方法时追加到现有文件。

PrintStream 和 OutputStream 的区别:与上面的解释类似,只是将字符替换为字节。

PrintWriter 有以下方法:

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

和构造函数是:

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

而 FileWriter 有以下方法:

close()
flush()
write()

和构造函数是:

File
String 

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

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

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.

Similarities

  1. Both extend from Writer.
  2. Both are character representation classes, that means they work with characters and convert them to bytes using default charset.

Differences

  1. FileWriter throws IOException in case of any IO failure, this is a checked exception.
  2. None of the PrintWriter methods throw IOExceptions, instead they set a boolean flag which can be obtained using checkError().
  3. PrintWriter has an 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.

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

PrintWriter has following methods :

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

and constructors are :

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

while FileWriter having following methods :

close()
flush()
write()

and constructors are :

File
String 

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

知你几分 2024-11-09 15:53:19

这两者都在内部使用了 FileOutputStream:

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 提供了特殊方法:

打印格式化的表示
文本输出流的对象。这
类实现了所有的打印
在 PrintStream 中找到的方法。确实如此
不包含写入原始数据的方法
程序应使用的字节
未编码的字节流。

与 PrintStream 类不同,如果
自动冲洗已启用,它将
仅当 println 之一时才完成,
printf 或调用 format 方法,
而不是每当换行时
恰好输出了字符。这些
方法使用平台自己的概念
行分隔符而不是
换行符。

Both of these use a FileOutputStream internally:

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));
}

but the main difference is that PrintWriter offers special methods:

Prints formatted representations of
objects to a text-output stream. This
class implements all of the print
methods found in PrintStream. It does
not contain methods for writing raw
bytes, for which a program should use
unencoded byte streams.

Unlike the PrintStream class, if
automatic flushing is enabled it will
be done only when one of the println,
printf, or format methods is invoked,
rather than whenever a newline
character happens to be output. These
methods use the platform's own notion
of line separator rather than the
newline character.

一绘本一梦想 2024-11-09 15:53:19

PrintWriter 有不同的错误处理概念。您需要调用 checkError() 而不是使用 try/catch 块。

A PrintWriter has a different concept of error handling. You need to call checkError() instead of using try/catch blocks.

新一帅帅 2024-11-09 15:53:19

PrintWriter 不会抛出 IOException。为此,您应该调用 checkError() 方法。

PrintWriter doesn't throw IOException.You should call checkError() method for this purpose.

執念 2024-11-09 15:53:19

Java5+ 中的 java.io.PrintWriter 允许使用方便的方法/构造函数写入文件。
来自 Javadoc;

使用指定的文件创建一个新的 PrintWriter,不自动行刷新。这个方便的构造函数创建必要的中间 OutputStreamWriter,它将使用 Java 虚拟机实例的默认字符集对字符进行编码。

The java.io.PrintWriter in Java5+ allowed for a convenience method/constructor that writes to file.
From the Javadoc;

Creates a new PrintWriter, without automatic line flushing, with the specified file. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will encode characters using the default charset for this instance of the Java virtual machine.

人│生佛魔见 2024-11-09 15:53:19

只是为了提供与 FileOutputStreamlush() 相关的 FLUSH 和 Close 方法相关的更多信息

---只是确保任何缓冲的数据完全写入磁盘并准备好之后再次写入流(或写入器)。

close() ----刷新数据并关闭所有文件句柄、套接字或其他任何内容。现在连接已丢失,您无法向outputStream 写入任何内容。

just to provide more info related to FLUSH and Close menthod related to FileOutputStream

flush() ---just makes sure that any buffered data is written to disk flushed compltely and ready to write again to the stream (or writer) afterwards.

close() ----flushes the data and closes any file handles, sockets or whatever.Now connection has been lost and you can't write anything to outputStream.

我一向站在原地 2024-11-09 15:53:19

事实上 java.io.FileWriter 依赖于平台的默认字符编码,这使得它对我来说毫无用处。您永远不应该对部署应用程序的环境做出任何假设。

The fact that java.io.FileWriter relies on the default character encoding of the platform makes it rather useless to me. You should never assume something about the environment where your app will be deployed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文