Basically I would like to know whether or not the PrintWriter is a Buffered Writer.
I have seen code like PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
However from this javadoc:
Parameters: file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
Bottom line: I think that PrintWriter is buffered since the javadoc "kind of mention it" (see the quote) and if I don't flush a PrintWriter it does not get printed.
Do you confirm my thesis? In that case why there is some code that goes like:
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
legacy code?
Thanks in advance.
Technically, it is not a BufferedWriter
. It directly extends Writer
. That said, it seems like it can use a BufferedWriter
depending on the constructor you call. For exampe look at the constructor that passes in a String
:
public PrintWriter(String fileName) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
false);
}
Also, you're not using the constructor for the javadoc you've linked to. You've used the constructor that takes a Writer
. That one does not seem to use a BufferedWriter
. This is its source code:
/**
* Creates a new PrintWriter, without automatic line flushing.
*
* @param out A character-output stream
*/
public PrintWriter (Writer out) {
this(out, false);
}
/**
* Creates a new PrintWriter.
*
* @param out A character-output stream
* @param autoFlush A boolean; if true, the <tt>println</tt>,
* <tt>printf</tt>, or <tt>format</tt> methods will
* flush the output buffer
*/
public PrintWriter(Writer out,
boolean autoFlush) {
super(out);
this.out = out;
this.autoFlush = autoFlush;
lineSeparator = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
}
来源:https://stackoverflow.com/questions/17223211/is-a-printwriter-a-bufferedwriter