浅谈打印流是真的自动刷新吗?

今天简单的谈谈java语言中IO流中的打印流的使用中的自动刷新。希望能给大家打来帮助,特别针对初学者。

首先,大家都知道这样的打印流的特性及优点吧: (1) 打印流都是输出流 (2)打印流是节点流 

          (3)打印流具有字符与字节的转换功能 (4)打印流可以自动刷新(是真的自动吗?)

现在我们就讨论打印流到底是不是真的自动刷新:(注:以PrintWriter为例)

首先我们先看看打印流的底层部分代码

	首先截取的是PrintWriter类中的用来判断是否可以自动刷新的私有属性,看到这个应该可以得到在构造器时会使用这个属性
	private final boolean autoFlush;
	好现在展示构造器的代码
构造器一: 
	public PrintWriter (Writer out) {
        this(out, false);
    	}
	
构造器二:
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"));
    }


	以上是PrintWriter的两个构造器。 由此可以看出如果调用构造器一的时候自动刷新的属性等于false 说明该构造器不带有自动刷新的功能。
	调用构造器二时需要指定他是否自动刷新,true 自动刷新,false 不自动刷新。

看到PrintWriter类的截取的部分代码是否明白点了呢。

但是重要的来了:是谁到底使用了这个autoFlush属性呢,只要使用构造器二并且指定为true所有的输出打印方法就可以自动刷新了吗?

其实并并不然。在构造器二中有这样的注释:

 /**
     * 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
     */
所以说只有println,printf,format才会执行自动刷新。其实我认为它还缺少一个方法没说 :newLine();----->println()方法可以实现自动刷新其实是调用了newLine()方法;

口说无凭源码为证:

先说println()和newLine():

 public void println(String x) {
        synchronized (lock) {
            print(x);
            println();
        }
   }

public void println() {
        newLine();
    }
 private void newLine() {
        try {
            synchronized (lock) {
                ensureOpen();
                out.write(lineSeparator);
                if (autoFlush)
                    out.flush();
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
            trouble = true;
        }
    }
所以说println()是因为调用newLine()才实现刷新功能的

对于printf,format和println与newLine关系相同。 format中有刷新功能,而printf的刷新是调用了format方法实现的。

PrintStream 同理可知,就不累述了。

总结:所以说PrintWriter的自动刷新功能是在使用 public PrintWriter(Writer out,boolean autoFlush)构造器,autoFlush为true,并且在使用println newLine printf format 才会实现。

你还认为PrintWriter是真的具有自动刷新功能吗(因为有限制)。

注:该文仅代表个人观点,如有不对请多多包涵,多多指教。



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值