Is PrintWriter buffered?
I have been studying for the SCJP exam and began wondering if PrintWriter is buffered. From what I can tell in the javadocs it seems to imply that it is; however, I keep seeing developer code that wraps a BufferedWriter.
Not that it matters for the exam (it can be done and that's all I need to know) but as it applies to the real world, is it necessary?
Any light shed on this would be appreciated.
Thanks.
[433 byte] By [
DMJasona] at [2007-11-27 7:55:14]

# 1
Yes it is buffered and that's what the autoflush parameter is there for.You should not wrap a PrintWriter, as it swallows exceptions, so you're just losing contact with the underlying realities. IMO you shouldn't use a PrintWriter on a socket either, for the same reason.
ejpa at 2007-7-12 19:36:33 >

# 2
Thanks for the information. I have been seeing a lot of code such as the following:
try{
FileWriter fw = new FileWriter("someFile.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
}catch(IOException ioe){
ioe.printStackTrace();
}
It seems to me that creating the BufferedWriter is redundant if the PrintWriter is buffered? I would just either create the PrintWriter or create the BufferedWriter.
So just to be certain, my intuition was correct? You shouldn't write code like that above?
# 3
On investigation it appears that in most cases the PrintWriter creates a BufferedWriter internally, in which case it is buffered, but in two cases it doesn't; in neither case does it create a buffer of its own so in the latter case it isn't buffered. So whether it is buffered depends on whether it created the BufferedWriter.
It has eight constructors, of which only the two that take a Writer don't create a BufferedWriter. It definitely creates a BufferedWriter in all the other cases, i.e. if the first constructor parameter is an OutputStream or a filename or a File. So the code you showed it actually non-redundant, but it could still be simplified to just new PrintWriter("someFile.txt") without any actual change in effect.
ejpa at 2007-7-12 19:36:33 >
