目前在學習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