How do I get a platform-dependent new line character?

前端 未结 9 1299
予麋鹿
予麋鹿 2020-11-22 02:17

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

相关标签:
9条回答
  • 2020-11-22 02:33
    StringBuilder newLine=new StringBuilder();
    newLine.append("abc");
    newline.append(System.getProperty("line.separator"));
    newline.append("def");
    String output=newline.toString();
    

    The above snippet will have two strings separated by a new line irrespective of platforms.

    0 讨论(0)
  • 2020-11-22 02:35

    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( );
    
    0 讨论(0)
  • 2020-11-22 02:36

    In addition to the line.separator property, if you are using java 1.5 or later and the String.format (or other formatting methods) you can use %n as in

    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   ^^
    

    See the Java 1.8 API for Formatter for more details.

    0 讨论(0)
  • 2020-11-22 02:36

    If you're trying to write a newline to a file, you could simply use BufferedWriter's newLine() method.

    0 讨论(0)
  • 2020-11-22 02:36

    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.

    0 讨论(0)
  • 2020-11-22 02:41

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

    0 讨论(0)
提交回复
热议问题