2

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.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Rollerball
  • 12,618
  • 23
  • 92
  • 161

1 Answers1

2

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"));
}
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • Ok so if constructed with a file/fileName it uses a BufferedWriter implicitly otherwise it has to be declared in the constructor? – Rollerball Jun 20 '13 at 20:44
  • Not exactly. It really depends on the constructor you use. You have to look at the source to be sure, or you can always create it like you did above and not have to think about it. – Daniel Kaplan Jun 20 '13 at 20:47
  • Why making it autoflushable if not buffered then? – Rollerball Jun 22 '13 at 08:32