How to write new line character to a file in Java

前端 未结 9 1559
执念已碎
执念已碎 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 07:04

    SIMPLE SOLUTION

    File file = new File("F:/ABC.TXT");
    FileWriter fileWriter = new FileWriter(file,true);
    filewriter.write("\r\n");
    
    0 讨论(0)
  • 2020-12-01 07:04

    bufferedWriter.write(text + "\n"); This method can work, but the new line character can be different between platforms, so alternatively, you can use this method:

    bufferedWriter.write(text);
    bufferedWriter.newline();
    
    0 讨论(0)
  • 2020-12-01 07:06

    Here is a snippet that gets the default newline character for the current platform. Use System.getProperty("os.name") and System.getProperty("os.version"). Example:

    public static String getSystemNewline(){
        String eol = null;
        String os = System.getProperty("os.name").toLowerCase();
        if(os.contains("mac"){
            int v = Integer.parseInt(System.getProperty("os.version"));
            eol = (v <= 9 ? "\r" : "\n");
        }
        if(os.contains("nix"))
            eol = "\n";
        if(os.contains("win"))
            eol = "\r\n";
    
        return eol;
    }
    

    Where eol is the newline

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