我正在尝试写一个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();
}
}
什么地方出了错?如何解决这个问题?谢谢你的帮助!
文本来自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));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)