写入文件的字符串不保留换行符

Aha*_*med 19 java string newline file

我想写一个String(冗长但包裹),来自JTextArea.当字符串打印到控制台时,格式化与它的格式相同Text Area,但是当我使用BufferedWriter将它们写入文件时,它正在String单行写入.

以下代码片段可以重现它:

public class BufferedWriterTest {
    public static void main(String[] args) throws IOException {
        String string = "This is lengthy string that contains many words. So\nI am wrapping it.";
        System.out.println(string);
        File file = new File("C:/Users/User/Desktop/text.txt");
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(string);
        bufferedWriter.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

什么地方出了错?怎么解决这个?谢谢你的帮助!

Kev*_*n K 18

来自a的文本JTextArea将具有\n换行符,无论其运行的平台如何.当您将这些字符写入文件时,您将希望将这些字符替换为特定于平台的换行符(对于Windows \r\n,正如其他人所提到的那样).

我认为最好的方法是将文本包装成a BufferedReader,可以用来遍历行,然后使用a PrintWriter将每行写入使用特定于平台的换行符的文件.有一个较短的解决方案string.replace(...)(见Unbeli评论),但速度较慢,需要更多内存.

这是我的解决方案 - 由于Java 8中的新功能,现在变得更加简单:

public static void main(String[] args) throws IOException {
    String string = "This is lengthy string that contains many words. So\nI am wrapping it.";
    System.out.println(string);
    File file = new File("C:/Users/User/Desktop/text.txt");

    writeToFile(string, file);
}

private static void writeToFile(String string, File file) throws IOException {
    try (
        BufferedReader reader = new BufferedReader(new StringReader(string));
        PrintWriter writer = new PrintWriter(new FileWriter(file));
    ) {
        reader.lines().forEach(line -> writer.println(line));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 嗯,堆叠所有这些读者做简单的更换?`string.replace("\\n",System.getProperty("line.separator"));` (2认同)

jlu*_*ick 7

请参阅以下有关如何正确处理换行的问题.

如何获得与平台相关的新行字符?

基本上你想用

String newLineChar = System.getProperty("line.separator");
Run Code Online (Sandbox Code Playgroud)

然后使用newLineChar而不是"\n"