问题描述
PrintStream
和 PrintWriter
有什么区别?它们有许多共同的方法,因此我经常将这两个类混合在一起.此外,我认为我们可以将它们用于完全相同的事情.但是必须有区别,否则就只有一个班级了.
What is the difference between PrintStream
and PrintWriter
? They have many methods in common due to which I often mix these two classes up. Moreover, I think we can use them for exactly the same things. But there has to be a difference, otherwise, there would have been only one class.
我搜索了档案,但找不到这个问题.
I have searched the archives, but couldn't find this question.
推荐答案
这可能听起来很轻率,但 PrintStream
打印到 OutputStream
和 PrintWriter
打印到 Writer
.好吧,我怀疑我会因为陈述明显的问题而得到任何分数.但还有更多.
This might sound flippant, but PrintStream
prints to an OutputStream
, and PrintWriter
prints to a Writer
. Ok, I doubt I'll get any points for stating the obvious. But there's more.
那么,OutputStream
和 Writer
之间有什么区别?两者都是流,主要区别在于 OutputStream
是字节流,而 Writer
是字符流.
So, what is the difference between an OutputStream
and a Writer
?Both are streams, with the primary difference being a OutputStream
is a stream of bytes while a Writer
is a stream of characters.
如果 OutputStream
处理字节,那么 PrintStream.print(String)
怎么样?它使用默认平台编码将字符转换为字节.使用默认编码通常是一件坏事,因为它会在从一个平台移动到另一个平台时导致错误,尤其是当您在一个平台上生成文件并在另一个平台上使用它时.
If an OutputStream
deals with bytes, what about PrintStream.print(String)
? It converts chars to bytes using the default platform encoding. Using the default encoding is generally a bad thing since it can lead to bugs when moving from one platform to another, especially if you are generating the file on one platform and consuming it on another.
使用 Writer
,您通常指定要使用的编码,避免任何平台依赖性.
With a Writer
, you typically specify the encoding to use, avoiding any platform dependencies.
为什么要在 JDK 中使用 PrintStream
,因为主要目的是写入字符,而不是字节?PrintStream
在引入 Reader/Writer 字符流时早于 JDK 1.1.我想 Sun 会弃用 PrintStream
,因为它被广泛使用.(毕竟,您不希望每次调用 System.out
都生成不推荐使用的 API 警告!此外,将类型从 PrintStream
更改为 PrintWriter标准输出流上的代码>会破坏现有的应用程序.)
Why bother having a PrintStream
in the JDK, since the primary intent is to write characters, and not bytes? PrintStream
predates JDK 1.1 when Reader/Writer character streams were introduced. I imagine Sun would have deprecated PrintStream
if only for the fact it is so widely used. (After all, you wouldn't want each call to System.out
to generate a deprecated API warning! Also, changing the type from PrintStream
to PrintWriter
on the standard output streams would have broken existing applications.)
这篇关于Java:PrintStream 和 PrintWriter 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!