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

发布于 2025-01-03 13:10:03 字数 719 浏览 2 评论 0原文

我正在尝试编写一个来自 JTextAreaString(很长但已包装)。当字符串打印到控制台时,格式与文本区域中的格式相同,但是当我使用 BufferedWriter 将它们写入文件时,它会在单行中写入该字符串。

以下片段可以重现它:

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();
    }
}

出了什么问题?如何解决这个问题?感谢您的帮助!

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 Text Area, but when I write them to file using BufferedWriter, it is writing that String in single line.

Following snippet can reproduce it:

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();
    }
}

What went wrong? How to resolve this? Thanks for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

对不⑦ 2025-01-10 13:10:03

来自 JTextArea 的文本将包含 \n 换行符,无论其运行在哪个平台上。将这些字符写入文件时,您需要将这些字符替换为特定于平台的换行符(对于 Windows,这是 \r\n,正如其他人提到的)。

我认为最好的方法是将文本包装到 BufferedReader 中,它可用于迭代行,然后使用 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));
    }
}

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).

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.

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));
    }
}
网名女生简单气质 2025-01-10 13:10:03

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

如何获得依赖于平台的换行符字符?

基本上你想使用

String newLineChar = System.getProperty("line.separator");

然后使用 newLineChar 而不是“\n”

Please see the following question on how to appropriately handle newlines.

How do I get a platform-dependent new line character?

Basically you want to use

String newLineChar = System.getProperty("line.separator");

and then use the newLineChar instead of "\n"

傲鸠 2025-01-10 13:10:03

我刚刚运行了你的程序,并在换行符(\n)之前添加了一个回车符(\r),这对我来说很有效。

如果你想获得一个独立于系统的行分隔符,可以在系统属性 line.separator 中找到一个

String separator = System.getProperty("line.separator");
String string = "This is lengthy string that contains many words. So" + separator
            + "I am wrapping it.";

I just ran your program, and adding a carriage return (\r) before your newline (\n) did the trick for me.

If you want to get a system independent line separator, one can be found in the system propery line.separator

String separator = System.getProperty("line.separator");
String string = "This is lengthy string that contains many words. So" + separator
            + "I am wrapping it.";
夏花。依旧 2025-01-10 13:10:03

如果您希望将 Java 字符串中的回车符保留到文件中。只需按照以下语句替换每个换行符(在 java 中被识别为:\n):

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

这是一个代码示例,

        // 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);

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);
心凉怎暖 2025-01-10 13:10:03

如果您使用 BufferedWriter,还可以使用 .newline() 方法根据您的平台重新添加换行符。

请参阅此相关问题: 写入文件的字符串不保留换行符

If you are using a BufferedWriter, you could also use the .newline() method to re-add the newline based on your platform.

See this related question: Strings written to file do not preserve line breaks

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文