Difference between java.io.PrintWriter and java.io.BufferedWriter? - java

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?

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

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.

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")));

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.

PrintWriter is the most enhanced Writer to write Character data to a file.
The main advantage of PrintWriter over FileWriter and BufferedWriter is:
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);
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

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.

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.

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);

Related

I/O Character stream: BufferedReader vs printWriter construction

Why is BufferedReader created as such
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
while PrintWriter can be simply constructed like these
PrintWriter pw = new PrintWriter(System.out, true);
BufferedReader can't be constructed directly from System.in so it requires InputStreamReader to convert bytes to char, is this to make it human readable? But PrintWriter dosen't require a wrap from char back to bytes why is that so, does Java automate it? Because to a machine everything is 1 & 0 anyway.
so it requires InputStreamReader to convert bytes to char, is this to
make it human readable?
No, it's for performance. Check this to see the difference between them.
And there are BufferedWriter and BufferedReader, they have similar functions and constructors.
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new PrintWriter(System.out));
First:
- Binary data: byte[], InputStream, OutputStream;
- (Unicode) text: String, char, Reader, Writer;
- Bridges where binary data has some encoding/Charset and is actually text: InputStreamReader, OutputStreamWriter (converting from/to given or default Charset).
Now consider:
System.in is a InputStream.
System.out and System.err are a PrintStream extending from OutputStream.
They are conceived as for binary data, which for Unix is quite normal and useful. For a console however not so useful. However PrintStream might be a design mishap/error: it has text support, also for passing a Charset; it is a half OutputStreamWriter.
So see PrintStream as an old unclean class doing what an OutputStreamWriter + BufferedWriter does, however not being a Writer.
BufferedWriter+OutputStreamWriter has the same complexity (though being reversed) as PrintStream. One also sees Scanner: new Scanner(System.in). This is not a Reader, and has superfluous support for tokenizing. It like PrintStream has the advantage of briefness, but is definitely more unclean for its unneeded overhead. (There are quite a lot of bugs mentioned in StackOverflow on Scanner.)

Count the bytes written to file via BufferedWriter

I am using BufferedWriter to write text with specific encoding to file, I want to count the file size in bytes before I close the file.
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),encoding),bsize);
bw.write(string);
My plan was to use string.getBytes() but this method doesn't allow to provide specific encoding (and I can't override the default encoding property).
Use String#getBytes(encoding) instead
If you're looking for a method that works regardless of whether you're appending or not and does not duplicate data just for counting, store the reference to the FileOutputStream in a variable and access the FileChannel through getFileChannel(). You can call long position() before and after the data has been written, and the difference of the values will give you the number of bytes that have been written.

PrintWriter vs FileWriter in the following context [duplicate]

This question already has answers here:
PrintWriter vs FileWriter in Java
(7 answers)
Closed 9 years ago.
What if in the next bit of code I am going to substitute (new FileWriter with (new PrintWriter
pw = new PrintWriter(new BufferedWriter(new FileWriter ("xanaduindeed.txt")));
pw = new PrintWriter(new BufferedWriter(new PrintWriter ("xanaduindeed.txt")));
Both of them work fine, however I would like to know which of the two optimize the memory usage. (if either of the two is actually better)
Thanks in advance.
In Oracle's JVM:
public PrintWriter(String fileName) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
false);
}
PrintWriter's notable characteristic is to flush output on every newline (LF or CR or CRLF). Lowest memory footprint would be a bare FileWriter, but buffering gives a notable improvement in I/O performance.
The main thing I'd worry about is exception handling being different for both cases. Check out this older answer here
In either case though, be careful with the encoding! You're taking yout system's default, so something you write on your computer might be misread in another
The best solution is
new PrintWriter ("xanaduindeed.txt")));
it uses BufferedWriter internally and writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. You dont need to try and optimize it further.

FileWrite BufferedWriter and PrintWriter combined

Ok so I am learning about I/O, and I found the following code in one of the slides. can someone please explain why there is a need to have a FileWrite, BufferedWriter and PrintWriter? I know BufferedWriter is to buffer the output and put it all at once but why would they use FileWriter and PrintWriter ? dont they pretty much do the same with a bit of difference in error handling etc?
And also why do they pass bw to PrintWriter?
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
Presumably they're using a FileWriter because they want to write to a file. Both BufferedWriter and PrintWriter have to be given another writer to write to - you need some eventual destination.
(Personally I don't like FileWriter as it doesn't let you specify the encoding. I prefer to use FileOutputStream wrapped in an OutputStreamWriter, but that's a different matter.)
BufferedWriter is used for buffering, as you say - although it doesn't buffer all the output, just a fixed amount of it (the size of the buffer). It creates "chunkier" writes to the underlying writer.
As for the use of PrintWriter - well, that exposes some extra methods such as println. Personally I dislike it as it swallows exceptions (you have to check explicitly with checkError, which still doesn't give the details and which I don't think I've ever seen used), but again it depends on what you're doing. The PrintWriter is passed the BufferedWriter as its destination.
So the code below the section you've shown will presumably write to the PrintWriter, which will write to the BufferedWriter, which will (when its buffer is full, or it's flushed or closed) write to the FileWriter, which will in turn convert the character data into bytes on disk.
From the Docs:
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,
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.
You can understand from this that a BufferedWriter is an efficient way to write stuff.
Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
A FileWriter object is passed to the BufferedWriter as the intent here is to write to some output file using a BufferedWriter.
And finally, a PrintWriter is used for print* methods like println().
PrintWriter from here
Prints formatted representations of objects to a text-output stream.
This class implements all of the print methods found in PrintStream.
It does not contain methods for writing raw bytes, for which a program
should use unencoded byte streams.
from the above statement it seems the main reason to use PrintWriter is to get the access of all the methods of PrintStream like println(),println(char [] x) etc.
BufferedWriter, You are right It's one of the best way to write to a file because it will buffered the character into the virtual memory before writing to a file directly and came up with a newLine() method.
FileWriter from here
FileWriter is meant for writing streams of characters. For writing
streams of raw bytes, consider using a FileOutputStream
.
FileWriter is simply to write plain text(without formatting) it doesn't use any buffer mechanism, whatever comes its way it just writes.
BufferedWriter is a wrapper for Writer classes to allow it to be able to use buffer functionality (to optimize IO).
PrintWriter prints formatted text, you can provide format string along with the data to be printed, though it can directly work with any Writer/OutputStream, just to provide buffering, Writer/OutputStream is 1st passed to BufferedWriter then to have formatted text is passed to PrintWriter
Usually, this kind of Writer chaining is about abstraction. PrintWriter have some useful print and println methods that can be convenient if you want to print Strings and lines to a File. Working directly with FileWriter, you would have to use a more "low level" API. And as you say BufferedWriter is about buffering. So it's basically a matter of what you want to output to the file, and what level of abstraction you prefer.
The objects are wrapped in this order because you want to use the outermost PrintWriter for its more sophisticated formatting. BufferedWriter must be wrapped on something. So FileWriter, as a result, is what BufferedWriter wraps and is the innermost object.

In Java, what is the advantage of using BufferedWriter to append to a file?

I'm looking at the following example
Which uses the following code
try {
BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
out.write("aString");
out.close();
}
catch (IOException e) {}
What's the advantage over doing
FileWriter fw = new FileWriter("outfilename");
I have tried both and they seem comparable in speed when it comes to the task of appending to a file one line at a time
The Javadoc provides a reasonable discussion on this subject:
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,
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.
If you're writing large blocks of text at once (like entire lines) then you probably won't notice a difference. If you have a lot of code that appends a single character at a time, however, a BufferedWriter will be much more efficient.
Edit
As per andrew's comment below, the FileWriter actually uses its own fixed-size 1024 byte buffer. This was confirmed by looking at the source code. The BufferedWriter sources, on the other hand, show that it uses and 8192 byte buffer size (default), which can be configured by the user to any other desired size. So it seems like the benefits of BufferedWriter vs. FileWriter are limited to:
Larger default buffer size.
Ability to override/customize the buffer size.
And to further muddy the waters, the Java 6 implementation of OutputStreamWriter actually delegates to a StreamEncoder, which uses its own buffer with a default size of 8192 bytes. And the StreamEncoder buffer is user-configurable, although there is no way to access it directly through the enclosing OutputStreamWriter.
this is explained in the javadocs for outputstreamwriter. a filewriter does have a buffer (in the underlying outputstreamwriter), but the character encoding converter is invoked on each call to write. using an outer buffer avoids calling the converter so often.
http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStreamWriter.html
A buffer effectivity is more easily seen when the load is high. Loop the out.write a couple thousand of times and you should see a difference.
For a few bytes passed in just one call probably the BufferedWriter is even worse (because it problably later calls FileOutputStream).

Categories