关于JAVA中流的flush问题

目前在学习Socket,因为和IO关系紧密,于是顺便也学了下IO

发现有这样一句话:

The flush method is valid on any output stream,but has no effect unless the stream is buffered

这句话意思是所有的输出流都有flush方法,但是仅对缓冲流有效

看到这里,笔者想到了自己写的serversocket类,部分代码如下,没有用buffered流也调用了flush方法啊?于是进行了一番探讨

private OutputStream ous;
ous = socket.getOutputStream();
public void sendMsg(String msg){
		PrintWriter out = new PrintWriter(ous);
		out.println("消息:"+msg);
		out.flush();
}

看到这里用PrintWriter包装了OutputStream流,OutputStream肯定为非缓冲流,所以问题一定出在PrintWriter上

让我们来看一下PrintWriter的底层代码,部分相关代码如下

public class PrintWriter extends Writer {
    protected Writer out;
    private final boolean autoFlush;

     /**
     * Creates a new PrintWriter, without automatic line flushing.
     *
     * @param  out        A character-output stream
     */
    public PrintWriter (Writer out) {
        this(out, false);
    }
     /**
     * 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
     */
    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"));
    }
    public PrintWriter(OutputStream out) {
        this(out, false);
    }
}
如上所示,这样我们就很清楚了,当调用包装OutputStream的构造方法时,autoFlush参数是falus


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值