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>).
   */
    在我機器上測試,默認的lineSeparator輸出的十六進制爲13 10即\r\n
    這樣write方法修改爲:write(str+"\r\n")即達到了與println(str)一樣的效果了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章