-->

Why need PrintWriter?

2020-05-27 15:28发布

问题:

I am really confused about the purpose of various io classes, for example, If we have BufferedWriter, why we need a PrintWriter?

BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;      
while(s=br.readline()!=null) {
      PrintWriter fs = new PrintWriter(new FileWriter(file));
      fs.println(s);
}

if the BufferedWriter can not help? I just do not understand the difference between these io classes, can someone explain me?

回答1:

They have nothing to do with each other. In all truth, I rarely use PrintWriter except to convert System.out temporarily. But anyway.

BufferedWriter, like BufferedReader/BufferedInputStream/BufferedOutputStream merely decorates the enclosed Writer with a memory buffer (you can specify the size) or accept a default. This is very useful when writing to slow Writers like network or file based. (Stuff is committed in memory and only occasionally to disk for example) By buffering in memory the speed is greatly increased - try writing code that writes to say a 10 mb file with just FileWriter and then compare to the same with BufferedWriter wrapped around it.

So that's BufferedWriter. It throws in a few convenience methods, but mostly it just provides this memory buffer.

PrintWriter mostly is a simple decorator that adds some specific write methods for various types like String, float, etc, so you don't have to convert everything to raw bytes.

Edited:

This already has come up



回答2:

The PrintWriter is essentially a convenience class. If you want to quickly and easily blast out a line of text to e.g. a log file, PrintWriter makes it very easy.

Three features:

  • The print and println methods will take any data type and do the conversion for you. Not just String.
  • The relatively new format method is worth its weight in gold. Now it's as simple in Java as in C to output a line of text with C-style format control.
  • The methods never throw an exception! Some programmers are horrified at the possibility of never hearing about things going wrong. But if it's a throwaway program or doing something really simple, the convenience can be nice. Especially if output is to System.out or System.err which have few ways of going wrong.


回答3:

The main reason to use the PrintWriter is to get access to the printXXX methods (like println(int)). You can essentially use a PrintWriter to write to a file just like you would use System.out to write to the console.

A BufferedWriter is an efficient way to write to a file (or anything else) as it will buffer the characters in Java memory before writing to the file.