我知道,如果我们想要编写格式化的数据,PrintWriter是非常好的,我也知道如何使用BufferedWriter来提高IO性能。
但我尝试过这样的方法,
PrintWriter pw = new PrintWriter(System.out);
pw.println("Statement 1");
pw.println("Statement 2");
//pw.flush();我注意到,当注释刷新方法时,没有输出,但当我取消注释时,我得到了所需的输出。
--这只有在PrintWriter被缓冲的情况下才有可能。如果是这样,那么使用BufferedWriter包装PrintWriter并编写它有什么意义?
--尽管javadoc没有提到PrintWriter是缓冲的,但似乎是这样的。
发布于 2015-08-24 08:52:12
我检查了以1.6.0_45开头的JDK版本,所有版本都有这构造函数:
/**
* 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);因此,PrintWritter使用缓冲输出。如果您想使用您指出的代码,您可以创建PrintWriter,将自动刷新设置为true,这将确保使用普林顿、printf或格式化方法之一刷新流。因此,您的代码在给定的上下文中如下所示:
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("Statement 1");
pw.println("Statement 2");发布于 2015-08-24 08:36:17
来自PrintWriter的Java8源代码
/**
* 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);您可以看到,PrintWriter使用BufferedWriter,并且它有一个选项autoFlush,只有在缓冲时才有意义。
发布于 2015-08-24 08:42:10
PrintWriter被缓冲。不同之处在于,PrintWriter为编写println()和printf()等对象的格式化字符串表示提供了方便的方法。它也有自动冲洗(所以很明显它有一个缓冲区)。
这两个类都是有效的。如果您启用了PrintWriter的自动刷新功能,那么它可能会更少(因为每次调用类似println()的东西时,它都会刷新),另一个不同之处是,PrintWriter并不真正允许您直接写入字节。
https://stackoverflow.com/questions/32177690
复制相似问题