How do I get a platform-dependent new line charact

2018-12-31 04:31发布

How do I get a platform-dependent newline in Java? I can’t use "\n" everywhere.

9条回答
千与千寻千般痛.
2楼-- · 2018-12-31 04:45

This is also possible: String.format("%n").

Or String.format("%n").intern() to save some bytes.

查看更多
时光乱了年华
3楼-- · 2018-12-31 04:49

If you are writing to a file, using a BufferedWriter instance, use the newLine() method of that instance. It provides a platform-independent way to write the new line in a file.

查看更多
梦醉为红颜
4楼-- · 2018-12-31 04:51

Avoid appending strings using String + String etc, use StringBuilder instead.

String separator = System.getProperty( "line.separator" );
StringBuilder lines = new StringBuilder( line1 );
lines.append( separator );
lines.append( line2 );
lines.append( separator );
String result = lines.toString( );
查看更多
栀子花@的思念
5楼-- · 2018-12-31 04:52

The commons-lang library has a constant field available called SystemUtils.LINE_SEPARATOR

查看更多
刘海飞了
6楼-- · 2018-12-31 05:00

You can use

System.getProperty("line.separator");

to get the line separator

查看更多
墨雨无痕
7楼-- · 2018-12-31 05:01

Java 7 now has a System.lineSeparator() method.

查看更多
登录 后发表回答