Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

java - Is PrintWriter buffered?

I know that the PrintWriter is really good if we want to write formatted data, and I also know the use of BufferedWriter to improve IO performance.

But I tried something like this,

PrintWriter pw = new PrintWriter(System.out);
pw.println("Statement 1");
pw.println("Statement 2");
//pw.flush();

I observed that when the flush method is commented there is no output, but when I uncomment it, I get the desired output.

This is only possible if the PrintWriter is buffered. If so, then what is the point of wrapping a PrintWriter using a BufferedWriter and then writing it?

Though the javadoc doesn't mention anywhere that the PrintWriter is buffered, but it seems so.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the Java 8 source for PrintWriter

/**
 * Creates a new PrintWriter from an existing OutputStream.  This
 * convenience constructor creates the necessary intermediate
 * OutputStreamWriter, which will convert characters into bytes using the
 * default character encoding.
 *
 * @param  out        An 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
 *
 * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
 */
public PrintWriter(OutputStream out, boolean autoFlush) {
    this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);

You can see that PrintWriter uses BufferedWriter and that it has an option autoFlush which would only make sense if it was buffered.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...