PrintWriter write與println方法的區別


    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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM