Difference between java.io.PrintWriter and java.io.BufferedWriter?
Asked Answered
L

9

109

Please look through code below:

// A.class
File file = new File("blah.txt");
FileWriter fileWriter = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(fileWriter);

// B.class
File file = new File("blah.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bWriter = new BufferedWriter(fileWriter);

What is the difference between these two methods?

When should we use PrintWriter over BufferedWriter?

Lacedaemon answered 17/11, 2009 at 6:52 Comment(0)
P
72

The API reference for BufferedWriter and PrintWriter detail the differences.

The main reason to use the PrintWriter is to get access to the printXXX methods like println(). 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 get is probably java.util.Scanner.

Photo answered 17/11, 2009 at 6:57 Comment(4)
@TritonMan at some point it needs to interact with the OS, which means stepping outside of Java.Photo
but PrintWriter is also buffered, right? so it is not acutally a difference between them as your answer may suggestVernavernacular
PrintWriter is buffered, but the difference is the methods that print writer has. I don't think I implied anything...Photo
what you wrote about BufferedWriter - is it also true for PrintWriter or not? still not clear for me since I consider this answer to be about differencesVernavernacular
E
104

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...

Ethanol answered 17/11, 2009 at 7:4 Comment(3)
@WindyFields: No, PrintStream is an OutputStream. PrintWriter is a Writer.Ethanol
Thanks. "it swallows exceptions." Do you mean PrintWriter doesn't raise checked exceptions? How about unchecked excepitons?Contraction
@Ben: I was specifically talking about IOException, in that every other IO abstraction (Reader, Writer etc) declares that its methods throw IOException if something goes wrong - PrintWriter doesn't.Ethanol
P
72

The API reference for BufferedWriter and PrintWriter detail the differences.

The main reason to use the PrintWriter is to get access to the printXXX methods like println(). 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 get is probably java.util.Scanner.

Photo answered 17/11, 2009 at 6:57 Comment(4)
@TritonMan at some point it needs to interact with the OS, which means stepping outside of Java.Photo
but PrintWriter is also buffered, right? so it is not acutally a difference between them as your answer may suggestVernavernacular
PrintWriter is buffered, but the difference is the methods that print writer has. I don't think I implied anything...Photo
what you wrote about BufferedWriter - is it also true for PrintWriter or not? still not clear for me since I consider this answer to be about differencesVernavernacular
S
10

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")));
Subdebutante answered 17/11, 2009 at 7:7 Comment(2)
Remembering @Jons comment that the PrintWriter will swallow the exceptions. checkError should be called.Foist
At least in the current openJDK 8 implementation (and probably older versions), PrinterWriter already creates a BufferedWriter.Falcate
A
7

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.

Anet answered 17/11, 2009 at 7:15 Comment(0)
P
4

PrintWriter is the most enhanced Writer to write Character data to a file.

The main advantage of PrintWriter over FileWriter and BufferedWriter is:

  1. PrintWriter can communicate directly with the file, and can communicate via some Writer object also.

PrintWriter printwriter = new PrintWriter("blah.txt");

(or)

FileWriter filewriter = new FileWriter("blah.txt");
PrintWriter printwiter = new PrintWriter(filewriter);
  1. We can write any type of Primitive data directly to the file (because we have additional overloaded versions of PrintWriter methods i.e., print() and println()).

    printwriter.print(65); //65
    bufferedwriter.write(65); //A
    printwriter.println(true); //true

Papotto answered 20/9, 2018 at 21:33 Comment(0)
T
3

In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,

Note: Text content in the code blocks is automatically word-wrapped

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.

Trever answered 13/6, 2014 at 10:23 Comment(0)
T
0

BufferedWriter - Writes text to an output character stream, buffering characters from a character stream. PrintWriter - Prints formatted representations of objects to a text output stream.

Telophase answered 15/5, 2017 at 12:22 Comment(0)
P
0

FileWriter and BufferedWriter need an new line separator for each line, just imagine having to write 100 lines whereas PrintWriter has the println() method that does that. Most importantly, FileWriter and BufferedWriter can write char and String data types ONLY whereas PrintWriter can also write int, double, and boolean data types

Pursy answered 4/10, 2023 at 15:48 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Broadcaster
E
-1

I think that the reason behind using PrintWriter is already mentioned above but one of the important reason is you an pass a file object directly to the PrintWriter constructor which makes it easy to use it.

File file=new File(“newfile.txt”);
PrintWriter pw=new PrintWriter(file);
Evanish answered 20/1, 2014 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.