java输出换行的标准姿势_java输出换行的标准姿势"line.separator"

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=newBufferedWriter(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.

*

*@paramout A Writer

*@paramsz Output-buffer size, a positive integer

*

*@exceptionIllegalArgumentException If sz is <= 0*/

public BufferedWriter(Writer out, intsz) {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 line.separator, and is not necessarily a single

* newline (‘\n‘) character.

*

*@exceptionIOException If an I/O error occurs*/

public void newLine() throwsIOException {

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

* line.separator, and is not necessarily a single newline

* character (‘\n‘).

*/

在我机器上(windows)测试,默认的lineSeparator输出的十六进制为13 10即\r\n

这样write方法修改为:write(str+"\r\n")即达到了与println(str)一样的效果了。

http://blog.csdn.net/vhomes/article/details/6650576

原文:http://www.cnblogs.com/softidea/p/5496701.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值