本文介绍了Java:PrintStream和PrintWriter之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-12 20:25