Is PrintWriter buffered?

非 Y 不嫁゛ 提交于 2019-11-29 07:18:45

I checked JDK versions starting with 1.6.0_45 and all of them have this constructor present:

/**
 * 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);

Hence PrintWritter uses buffered output. If you would like to use the code you pointed out, you can create the PrintWriter with the autoflush set to true, that will ensure that using one of the println, printf or format methods would flush the stream. So, your code would look like this in the given context:

PrintWriter pw = new PrintWriter(System.out, true);
pw.println("Statement 1");
pw.println("Statement 2");

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.

PrintWriter is buffered. The difference is that PrintWriter offers convenience methods for writing formatted string representations of objects like println() and printf(). It also has auto-flushing (so obviously it has a buffer).

Both classes are efficient. If you enable PrintWriter's auto flushing, then it may be less so (because it will flush every time you call something like println()). Another difference is that PrintWriter doesn't really let you write bytes directly.

I think that since PrintWriter too can read the String at once, it would be using the buffer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!