How to write new line character to a file in Java

前端 未结 9 1558
执念已碎
执念已碎 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.

    0 讨论(0)
  • 2020-12-01 06:51

    Put this code wherever you want to insert a new line:

    bufferedWriter.newLine();
    
    0 讨论(0)
  • 2020-12-01 06:53

    The BufferedWriter class offers a newLine() method. Using this will ensure platform independence.

    0 讨论(0)
  • 2020-12-01 06:55

    This approach always works for me:

    String newLine = System.getProperty("line.separator");
    String textInNewLine = "this is my first line " + newLine + "this is my second 
    line ";
    
    0 讨论(0)
  • 2020-12-01 06:57
        PrintWriter out = null; // for writting in file    
        String newLine = System.getProperty("line.separator"); // taking new line 
        out.print("1st Line"+newLine); // print with new line
        out.print("2n Line"+newLine);  // print with new line
        out.close();
    
    0 讨论(0)
  • 2020-12-01 07:02

    Split the string in to string array and write using above method (I assume your text contains \n to get new line)

    String[] test = test.split("\n");
    

    and the inside a loop

    bufferedWriter.write(test[i]);
    bufferedWriter.newline();
    
    0 讨论(0)
提交回复
热议问题