写入文件的字符串不保留换行符 [英] Strings written to file do not preserve line breaks
问题描述
我正在尝试写一个字符串
(冗长但已包装),它来自 JTextArea
。当字符串打印到控制台时,格式化与 Text Area
中的格式相同,但是当我使用BufferedWriter将它们写入文件时,它正在编写字符串
单行。
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!
推荐答案
来自 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));
}
}
这篇关于写入文件的字符串不保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!