views:

3345

answers:

4

Please look through the below code,

// A.java
File file=new File("blah.txt");
FileWriter fwriter=new FileWriter(file);
PrintWriter pwriter=new PrintWriter(fwriter);

//B.java
File file=new File("blah.txt");
FileWriter fwriter=new FileWriter(file);
BufferedWriter bwriter=new BufferedWriter(bwriter);

What is the difference between these two files? And when do we need to go for PrintWriter and BufferedReader/BufferedWriter?

+6  A: 

http://java.sun.com/javase/6/docs/api/java/io/BufferedWriter.html and http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html detail the differences.

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 (probably, depending on the implementation) dropping to C to do the writing to the file.

There is no such concept as a "PrintReader" the closest you will come is probably java.util.Scanner.

TofuBeer
+7  A: 

PrintWriter gives more methods (println), but the most important (and worrying) difference to be aware of is that it swallows exceptions.

You can call checkError later on to see whether any errors have occurred, but typically you'd use PrintWriter for things like writing to the console - or in "quick 'n dirty" apps where you don't want to be bothered by exceptions (and where long-term reliability isn't an issue).

I'm not sure why the "extra formatting abilities" and "don't swallow exceptions" aspects are bundled into the same class - formatting is obviously useful in many places where you don't want exceptions to be swallowed. It would be nice to see BufferedWriter get the same abilities at some point...

Jon Skeet
+3  A: 

As said in TofuBeer's answer both have their specialties. To take the full advantage of PrintWriter (or any other writer) but also use buffered writing you can wrap the BufferedWriter with the needed one like this:

PrintWriter writer = new PrintWriter(
                         new BufferedWriter (
                             new FileWriter("somFile.txt")));
Kai
Remembering @Jons comment that the PrintWriter will swallow the exceptions. checkError should be called.
MadMurf
+2  A: 

PrintWriter just exposes the print methods on any Writer in character mode.

BufferedWriter is more efficient than , according to its buffered methods. And it comes with a newLine() method, depending of your system platform, to manipulate text files correctly.

The BufferedReader permits to read a text from file, with bytes converted in characters. It allows to read line by line.

There is no PrintReader, you have to choose another Reader implementation according to the format of your input.

LDU
Since its a character stream where comes the "Bytes"...
i2ijeya