java - 逐行写入文本文件

标签 java swing file-io jtextarea filewriter

我试图从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/

相关文章:

java - 如何制作共享/实用支持 bean?

java - Guava CacheBuilder 最大尺寸

delphi - 如果父应用程序由其他目录中的应用程序启动,则文件I/O无法正常工作

c - 在 Windows 上格式化文件

java - Android:每次我想登录时是否打开文件资源

java - JaxB 属性值已定义。使用 <jaxb :property> to resolve this conflict

java - 如何使用 Spring Boot 针对真实数据库而不是在内存中一次性运行 @DataJpaTest

java - JPanel 中的重绘查询

java - 带有复选框和 JFileChooser 的 Swing JTree

java - BorderLayout,无法设置手动位置 - SWING Java