BufferedWriter類的newLine方法
源碼:
/**
* Writes a line separator. The line separator string is defined by the
* system property <tt>line.separator</tt>, and is not necessarily a single
* newline ('/n') character.
*
* @exception IOException If an I/O error occurs
*/
public void newLine() throws IOException {
write(lineSeparator);
}
BufferedWriter類的概述
/**
* Writes text to a character-output stream, buffering characters so as to
* provide for the efficient writing of single characters, arrays, and strings.
*
* <p> The buffer size may be specified, or the default size may be accepted.
* The default is large enough for most purposes.
*
* <p> A newLine() method is provided, which uses the platform's own notion of
* line separator as defined by the system property <tt>line.separator</tt>.
* Not all platforms use the newline character ('/n') to terminate lines.
* Calling this method to terminate each output line is therefore preferred to
* writing a newline character directly.
*
* <p> In general, a Writer sends its output immediately to the underlying
* character or byte stream. Unless prompt output is required, it is advisable
* to wrap a BufferedWriter around any Writer whose write() operations may be
* costly, such as FileWriters and OutputStreamWriters. For example,
*
* <pre>
* PrintWriter out
* = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
* </pre>
*
* will buffer the PrintWriter's output to the file. Without buffering, each
* invocation of a print() method would cause characters to be converted into
* bytes that would then be written immediately to the file, which can be very
* inefficient.
*
* @see PrintWriter
* @see FileWriter
* @see OutputStreamWriter
*
* @version 1.29, 05/11/30
* @author Mark Reinhold
* @since JDK1.1
*/
public class BufferedWriterextends Writer將文本寫入字元輸出資料流,緩衝各個字元,從而提供單個字元、數組和字串的高效寫入。
可以指定緩衝區的大小,或者接受預設的大小。在大多數情況下,預設值就足夠大了。
該類提供了 newLine() 方法,它使用平台自己的行分隔字元概念,此概念由系統屬性 line.separator 定義。並非所有平台都使用新行符 ('/n') 來終止各行。因此調用此方法來終止每個輸出行要優於直接寫入新行符。
通常 Writer 將其輸出立即發送到底層字元或位元組流。除非要求提示輸出,否則建議用 BufferedWriter 封裝所有其 write() 操作可能開銷很高的 Writer(如 FileWriters 和 OutputStreamWriters)。例如,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
將緩衝 PrintWriter 對檔案的輸出。如果沒有緩衝,則每次調用 print() 方法會導致將字元轉換為位元組,然後立即寫入到檔案,而這是極其低效的。