首页 文章

如何获得与平台相关的新行字符?

提问于
浏览
501

如何在Java中获得与平台相关的换行符?我到处都不能使用 "\n" .

9 回答

  • 22

    如果要使用 BufferedWriter 实例写入文件,请使用该实例的 newLine() 方法 . 它提供了一种独立于平台的方式来在文件中写入新行 .

  • -2

    Java 7现在有一个System.lineSeparator()方法 .

  • 347
    StringBuilder newLine=new StringBuilder();
    newLine.append("abc");
    newline.append(System.getProperty("line.separator"));
    newline.append("def");
    String output=newline.toString();
    

    上面的代码片段将有两个由新行分隔的字符串,与平台无关 .

  • 12

    您可以使用

    System.getProperty("line.separator");
    

    得到行分隔符

  • 9

    如果你're trying to write a newline to a file, you could simply use BufferedWriter' s newLine()方法 .

  • 28

    除了line.separator属性之外,如果您使用的是java 1.5或更高版本以及 String.format (或其他 formatting 方法),则可以使用 %n ,如

    Calendar c = ...;
    String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY%n", c); 
    //Note `%n` at end of line                                  ^^
    
    String s2 = String.format("Use %%n as a platform independent newline.%n"); 
    //         %% becomes %        ^^
    //                                        and `%n` becomes newline   ^^
    

    有关详细信息,请参阅Java 1.8 API for Formatter .

  • 638

    这也是可能的: String.format("%n") .

    String.format("%n").intern() 保存一些字节 .

  • 636

    commons-lang库有一个常量字段,名为SystemUtils.LINE_SEPARATOR

  • 43

    避免使用String String等附加字符串,而是使用StringBuilder .

    String separator = System.getProperty( "line.separator" );
    StringBuilder lines = new StringBuilder( line1 );
    lines.append( separator );
    lines.append( line2 );
    lines.append( separator );
    String result = lines.toString( );
    

相关问题