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.
Related
I'm having trouble understanding how do buffers work in Java IO.
Excuse me if I don't express myself as clearly as I would like, I'm not
strong on all these concepts.
As I undestand it, in Java there are readers/writers, for chars (meaning the
possibility of more than one byte per char and encoding options), and streams
for bytes.
Then there are some classes that use buffers.
I believe that a buffer is used mainly so that we can avoid unnecessary system
calls that would involve expensive operations, like accesing a slower device, by
storing more in memory and making the system call useful for more data.
The issue I have is that there seem to be buffering classes for both readers/writers and streams.
I would like to know if buffering characters is enough, or if, by the time those
bytes get to the streaming class, they would be flushed on for example newlines,
as some classes state.
The best I've found about this is this post
How do these different code snippets compare in regard to buffering?
Does autoflush thwart the intent of buffering?
Should there be only one buffer in play, and if so, where (writer or stream)
and why?:
// resolveSocket is some socket
PrintWriter out = new PrintWriter(
resolveSocket.getOutputStream(),
true);
// vs
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
new BufferedOutputStream(resolveSocket.getOutputStream()),
StandardCharsets.UTF_8),
true)
My interest is first and foremost to understand buffering better, and practical only after that.
Thak you all in advance.
EDIT: Found this other stack overflow question interesting and related.
Also this other one talks about BufferedOutputStream.
It may help you to understand the difference between a writer and a stream. An OutputStream is a binary sink. A Writer has a character encoding and understands about newlines. The OutputStreamWriter allows you to send character encoded data, and have it correctly translated to binary for consumption by an OutputStream. What you probably want is:
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(resolveSocket.getOutputStream())));
This will allow you to use your PrintWriter to output chars, have it buffered by the BufferedWriter, and then translated by the OutputStreamWriter for consumption by the socket output stream.
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.
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).
My question is about line (edit: 19), where the new PrintWriter is created with the constructor taking the FileWriter fw as a parameter. I don't understand the use of chaining the BufferedWriter bw to FileWriter if it isn't used later on in the actual writing. Can Java apply chaining in a way that bw still somehow affects the rest of the program?
16. try {
17. FileWriter fw = new FileWriter(test);
18. BufferedWriter bw = new BufferedWriter(fw, 1024);
19. PrintWriter out = new PrintWriter(fw);
20. out.println("<html><body><h1>");
21. out.println(args[0]);
22. out.println("</h1></body></html>");
23. out.close();
24. bw.close();
25. fw.close();
26. }catch(IOException e) {
27. e.printStackTrace();
28. }
I think it is probably a typo and they meant to use bw as the parameter for PrintWriter out but like the title says, I'm new to this.
Thanks to all in advance.
You are correct, this looks like a typo.
Line 18 should have no affect on the outcome of running this code.
The BufferedWriter Javadoc shows a normal example of how FileWriter, BufferedWriter and PrintWriter are typically used.
Which exact book is this? There are a few--the first place to look would be to go to the publisher's page for the book and look for the errata section. Chances are good that this is an error because, no, Java isn't chaining these particular objects (chaining wouldn't really be the right word, that would be more of a side effect). If you do find the errata page and it's not listed, you could always submit it to the authors via the site, and let them decide.
It compiles and produces the same result either way, but yeah, it looks like a typo.
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);