IO中flush()函数的使用

The java.io.Writer.flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.

public class Demo {
    public static void main(String[] ars) throws Exception {
        System.out.println("hello");
        PrintWriter writer = new PrintWriter(System.out);
        writer.println("writer start");
//      writer.flush();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        writer.println("writer close");
        writer.close();
    }
}

如上面代码,如果flush()被注释掉,则打印完“hello”之后3秒才会打印”writer start”,”writer close”,因为writer.close()在关闭输出流前会调用一次flush()。效果如下:
这里写图片描述
如果flush()没有被注释掉,则则打印完“hello”之后会立即打印”writer start”。
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值