JTextArea txt; txt.getText()跳过" \ n" [英] JTextArea txt; txt.getText() skips "\n"
问题描述
我在TextArea中有一些文本,我想将其保存在文件中,我的代码在这里:
i have some text in TextArea, and i want to save it in file, my code is here:
private void SaveFile() {
try {
String content = txt.getText();
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
但不保存\ N;在新文件中,一切都在一行;
我可以预见那些进入吗?
提前谢谢
but it saves without "\n"; and in new file everything is on one line; ho can i foresee those "enters" too? thank you in advance
问题是因为记事本,所以这里有解决方案:
the problem was because of notepad, so here is solution:
private void SaveFile() {
try {
String content = txt.getText();
content = content.replaceAll("(?!\\r)\\n", "\r\n");
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
感谢您的帮助
推荐答案
它应该有效。尝试使用显示行结尾\ r和\ n的文本编辑器,看看会出现什么。
It should work. Try to use a text editor that display the line endings \r and \n and see what comes up.
如果你想确定文本文件可以由记事本等只能理解 \\\\ n
的Windows实用程序打开,你必须自己规范化:
If you want to be sure that the text file can be open by windows utilities like Notepad that only understand \r\n
, you have to normalize it yourself this way:
content = content.replaceAll("(?!\\r)\\n", "\r\n");
这将取代所有 \ n
谁序列 \ r \ n
前面没有 \ r
。
This will replace all \n
who is not preceded by a \r
by the sequence \r\n
.
这篇关于JTextArea txt; txt.getText()跳过" \ n"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!