PrintWriter在以下以pw代替,在寫client與server進行測試的通訊程序時,用pw.println(str)可以把數據發送給客戶端,而pw.write(str)卻不行!
查看源碼發現:
pw.println(str)方法是由write方法與println()方法組成,頁println()方法中執行了newLine()方法。
而 newLine()實現中有一條out.write(lineSeparator);
即println(str)方法比write方法中多輸出了一個lineSeparator字符;
其中lineSeparator實現為;lineSeparator = (String) java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));
而line.separator屬性跟據每個系統又是不一樣的。
println()方法的注釋說明中提到:
/**
* Terminates the current line by writing the line separator string. The
* line separator string is defined by the system property
* <code>line.separator</code>, and is not necessarily a single newline
* character (<code>'\n'</code>).
*/
----------------
上述引用他人之手,重點在於不是簡單的加上\r\n 之類的轉義來替換 上述提到的lineSeparator。
如果一定要用write(),就必須使用write()+println()的組合。
當然給flush()的還是要flush.除非你在構造的時候就已經對autoFlush進行了初始化為true的操作
感興趣的朋友可以在看看這里:http://www.oschina.net/question/101123_17855