java 将 JTextArea 内容写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10522022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing JTextArea content into file
提问by SK0004
I have one JTextArea and a Submit button in Java Swing. Need to write the content of textarea into a file with line breaks. I got the output like, it is written as one string in the file.
我在 Java Swing 中有一个 JTextArea 和一个提交按钮。需要将textarea的内容写入带换行符的文件中。我得到了这样的输出,它被写成文件中的一个字符串。
try {
BufferedWriter fileOut = new BufferedWriter(new FileWriter("filename.txt"));
String myString1 =jTextArea1.getText();
String myString2 = myString1.replace("\r", "\n");
System.out.println(myString2);
fileOut.write(myString2);
fileOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Please get me some suggestions
请给我一些建议
回答by Jeffrey
回答by MarioDS
Replace all \r and \n with:
将所有 \r 和 \n 替换为:
System.getProperty("line.separator")
This will make your code platform-independent and will write new lines to the files where necessary.
这将使您的代码独立于平台,并在必要时将新行写入文件。
Edit: since you use BufferedWriter, you could also use the newLine() method
编辑:由于您使用 BufferedWriter,您还可以使用newLine() 方法
回答by nnhthuan
Why did you replace \r
by \n
?
你为什么换成\r
了\n
?
The line separator should be "\r\n"
.
行分隔符应该是"\r\n"
.
回答by Thor
This is what i thought up of :
这是我想到的:
public void actionPerformed(ActionEvent event) {
BufferedWriter writer;
try {
writer = new BufferedWriter(new FileWriter("SimpleText.txt",
false));
text.write(writer);
writer.close();
JOptionPane.showMessageDialog(null, "File has been saved","File Saved",JOptionPane.INFORMATION_MESSAGE);
// true for rewrite, false for override
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error Occured");
e.printStackTrace();
}
}
Hope this helps
希望这可以帮助