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.****.net/vhomes/article/details/6650576