Strings written to file do not preserve line breaks

后端 未结 5 1690
执笔经年
执笔经年 2020-11-28 13:27

I am trying to write a String(lengthy but wrapped), which is from JTextArea. When the string printed to console, formatting is same as it was in

5条回答
  •  情书的邮戳
    2020-11-28 14:20

    If you wish to keep the carriage return characters from a Java string into a file. Just replace each break line character (which is recognized in java as: \n) as per the following statement:

    TempHtml = TempHtml.replaceAll("\n", "\r\n");

    Here is an code example,

            // When Execute button is pressed
            String TempHtml = textArea.getText();
            TempHtml = TempHtml.replaceAll("\n", "\r\n");
            try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/temp.html"))) {
                out.print(TempHtml);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(TempHtml);
    

提交回复
热议问题