码迷,mamicode.com
首页 > 编程语言 > 详细

关于JAVA中流的flush问题

时间:2014-11-12 11:53:08      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:java   character   socket   buffer   

目前在学习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


关于JAVA中流的flush问题

标签:java   character   socket   buffer   

原文地址:http://blog.csdn.net/ytingone/article/details/41039757

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!