How to write new line character to a file in Java

前端 未结 9 1566
执念已碎
执念已碎 2020-12-01 06:13

I have a string that contains new lines. I send this string to a function to write the String to a text file as:

    public static void writeResult(String wr         


        
9条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 06:49

    In EDIT 2:

    while((line = bufferedReader.readLine()) != null)
    {
      sb.append(line); //append the lines to the string
      sb.append('\n'); //append new line
    } //end while
    

    you are reading the text file, and appending a newline to it. Don't append newline, which will not show a newline in some simple-minded Windows editors like Notepad. Instead append the OS-specific line separator string using:

    sb.append(System.lineSeparator()); (for Java 1.7 and 1.8) or sb.append(System.getProperty("line.separator")); (Java 1.6 and below)

    Alternatively, later you can use String.replaceAll() to replace "\n" in the string built in the StringBuffer with the OS-specific newline character:

    String updatedText = text.replaceAll("\n", System.lineSeparator())

    but it would be more efficient to append it while you are building the string, than append '\n' and replace it later.

    Finally, as a developer, if you are using notepad for viewing or editing files, you should drop it, as there are far more capable tools like Notepad++, or your favorite Java IDE.

提交回复
热议问题