java中寫.txt文件,實現換行的幾種方法:
1.使用java中的轉義符"\r\n":
windows下的文本文件換行符:\r\n
linux/unix下的文本文件換行符:\r
Mac下的文本文件換行符:\n
1.String str="aaa";
2.str+="\r\n";
2.BufferedWriter的newline()方法:
FileOutputStream fos=new FileOutputStream("c;\\11.txt"); BufferedWriter bw=new BufferedWriter(fos); bw.write("你好"); bw.newline(); bw.write("java"); bw.newline();
/**
* Creates a new buffered character-output stream that uses an output
* buffer of the given size.
*
* @param out A Writer
* @param sz Output-buffer size, a positive integer
*
* @exception IllegalArgumentException If sz is <= 0
*/
public BufferedWriter(Writer out, int sz) {
super(out);
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.out = out;
cb = new char[sz];
nChars = sz;
nextChar = 0;
lineSeparator = (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
}
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);
}
3.使用System.getProperty()方法:
String str = "Output:"+System.getProperty("line.separator");
http://www.cnblogs.com/todoit/archive/2012/04/27/2473232.html
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>).
*/
在我機器上(windows)測試,默認的lineSeparator輸出的十六進制為13 10即\r\n
這樣write方法修改為:write(str+"\r\n")即達到了與println(str)一樣的效果了。
http://blog.csdn.net/vhomes/article/details/6650576
