我试图从jtextarea
写入文本,并应将其保存为文本文件。但是当运行程序时,文本是在单行中写入,而不是逐行写入。
例如:
我的输入:
abcd
eghi
asdasddkj
但是得到这样的输出
abcdeghiasdasddkj
这是我的代码:
private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
String text = jTextArea1.getText();
File file = new File("D:/sample.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pl=new PrintWriter(bw);
pl.println(text);
System.out.println(text);
pl.close();
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
最佳答案
the texts is writing in a single line not writing line by line
文档
仅存储“\n”来表示新的行字符串。换行字符串根据您使用的操作系统而有所不同。有些编辑器足够聪明,可以识别多个换行字符串,而其他编辑器则不然,因此您只能得到单行。
i am trying to write texts from jtextarea and should save it as a textfile
不要自己进行 IO。
而是使用 JTextArea
API 提供的 write(...)
方法。
关于java - 逐行写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27915902/