简体   繁体   中英

Why use Printwriter over PrintStream in Java for outputting human readable text

The java documentation says to use Printwriter over Printstream when dealing with text, but why is this so? I know Printwriter deals with character streams and Printstream deals with byte streams but their both bytes at the end of the day. And since Java 1.5 PrintStream has not been limited to using the platform default encoding; there are constructors that accepts a charset name. So what benefit does Printwriter have over Printstream?

PrintStream is ancient. Prefer PrintWriter . Actually, it's better to use neither since both classes swallow exceptions silently.

I suggest using an OutputStreamWriter wrapped by a BufferedWriter .

PrintStream cannot use a character encoding other than the default charset. If you need to write strings as UTF-8 bytes and the default JVM charset is Windows-1252 (as is the case when running Java on Windows), then PrintWriter can do that, and PrintStream cannot. That's the main difference, I think.

PrintWriter doesn't allow you to write a byte[] , while PrintStream does. Allowing direct writing of byte[] opens up the possibility of making mistakes by mixing character encodings which shouldn't be mixed.

PrintWriter allows you to write a char[] directly while PrintStream does not.

PrintWriter allows you to write a slice of a String without allocating a new String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM