我在TextArea中有一些文本,我想将其保存在文件中,我的代码如下:
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";并且在新文件中,所有内容都在一行上;我还能预见这些"enters“吗?提前谢谢你
这个问题是由记事本引起的,所以这里有一个解决方案:
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();
}
}感谢你的帮助
发布于 2013-03-19 01:56:29
应该能行得通。尝试使用显示行尾\r和\n的文本编辑器,看看会出现什么。
如果你想确保文本文件可以被像记事本这样的只理解\r\n的windows实用程序打开,你必须自己用这种方式来规范化它:
content = content.replaceAll("(?!\\r)\\n", "\r\n");这将用序列\r\n替换前面没有\r的所有\n。
发布于 2013-03-19 02:38:26
您应该使用Swing文本组件提供的read()和write()方法。有关详细信息,请参阅Text and New Lines。
如果希望输出包含特定的EOL字符串,则应在为文本组件创建文档后使用以下内容:
textComponent.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "\r\n");发布于 2013-03-19 01:51:28
\字符转义下一个字符,如您所说,\n将创建一个换行符。如果你想输出一个实际的\,你需要写下:
"\n“
https://stackoverflow.com/questions/15483350
复制相似问题