且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-13 22:02:16

来自 JTextArea 的文字将有 \ n 换行符的字符,无论其运行的平台如何。当您将这些字符写入文件时,您需要将这些字符替换为特定于平台的换行符(对于Windows,这是 \\\\ n ,正如其他人提到的那样)。

Text from a JTextArea will have \n characters for newlines, regardless of the platform it is running on. You will want to replace those characters with the platform-specific newline as you write it to the file (for Windows, this is \r\n, as others have mentioned).

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

I think the best way to do that is to wrap the text into a BufferedReader, which can be used to iterate over the lines, and then use a PrintWriter to write each line out to a file using the platform-specific newline. There is a shorter solution involving string.replace(...) (see comment by Unbeli), but it is slower and requires more memory.

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

Here is my solution - now made even simpler thanks to new features in 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));
    }
}