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.
This might sound flippant, but
PrintStreamprints to anOutputStream, andPrintWriterprints to aWriter. Ok, I doubt I’ll get any points for stating the obvious. But there’s more.So, what is the difference between an
OutputStreamand aWriter?Both are streams, with the primary difference being a
OutputStreamis a stream of bytes while aWriteris a stream of characters.If an
OutputStreamdeals with bytes, what aboutPrintStream.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.With a
Writer, you typically specify the encoding to use, avoiding any platform dependencies.Why bother having a
PrintStreamin the JDK, since the primary intent is to write characters, and not bytes?PrintStreampredates JDK 1.1 when Reader/Writer character streams were introduced. I imagine Sun would have deprecatedPrintStreamif only for the fact it is so widely used. (After all, you wouldn’t want each call toSystem.outto generate a deprecated API warning! Also, changing the type fromPrintStreamtoPrintWriteron the standard output streams would have broken existing applications.)