PrintWriter write与println方法的区别
? ? PrintWriter在以下以pw代替,在寫client與server進行測試的通訊程序時,用pw.println(str)可以把數(shù)據(jù)發(fā)送給客戶端,而pw.write(str)卻不行!
查看源碼發(fā)現(xiàn):
? ? pw.println(str)方法是由write方法與println()方法組成,頁println()方法中執(zhí)行了newLine()方法。
? ?而 newLine()實現(xiàn)中有一條out.write(lineSeparator);
? ? 即println(str)方法比write方法中多輸出了一個lineSeparator字符;?
? ?其中l(wèi)ineSeparator實現(xiàn)為;lineSeparator = (String) java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));
? ?而line.separator屬性跟據(jù)每個系統(tǒng)又是不一樣的。
? ?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 之類的轉(zhuǎn)義來替換 上述提到的lineSeparator。
如果一定要用write(),就必須使用write()+println()的組合。
當然給flush()的還是要flush.除非你在構(gòu)造的時候就已經(jīng)對autoFlush進行了初始化為true的操作
感興趣的朋友可以在看看這里:http://www.oschina.net/question/101123_17855
轉(zhuǎn)載于:https://www.cnblogs.com/draem0507/archive/2013/05/07/3065588.html
總結(jié)
以上是生活随笔為你收集整理的PrintWriter write与println方法的区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hdu 1003 A + B Probl
- 下一篇: Microsoft 邀您参加云对话!