简体   繁体   English

使用行分隔符将JTextArea中的内容保存到文件中

[英]Saving content from JTextArea into file with line separators

I have a problem with writing to file. 我在写入文件时遇到问题。

Generally I am creating simple text editor. 通常,我正在创建简单的文本编辑器。 I load file in this way: 我以这种方式加载文件:

try(BufferedReader br = new BufferedReader(new FileReader(currentlyEditedFile))) {
            String line = "";
            editor.setText("");
            while((line = br.readLine()) != null) {
                editor.append(line + "\n");
            }
        } catch(Exception ex) {
            ex.printStackTrace();
        }

and the after some modifications, I want to save(write) it back to the file. 经过一些修改后,我想将其保存(写)回文件中。

I am doing it in this way: 我这样做是这样的:

try(PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(currentlyEditedFile)))) {
            String[] lines = editor.getText().split("\\n");//Tried \n, \\n
            for(String s : lines)
                pw.println(s);
        } catch(Exception ex) {
            ex.printStackTrace();
        }

and the content goes to the file, but it is all in one line. 内容进入文件,但全部在一行中。 Any ideas how to write line by line? 有什么想法如何逐行写吗?

You may load content of a text file into JTextArea in following simple way: 您可以通过以下简单方式将文本文件的内容加载到JTextArea中:

 JTextArea textArea = new JTextArea();
 FileReader reader = new FileReader("D:/text1.txt");
 textArea.read(reader, "Content of File");
 reader.close();

You may write content of JTextArea to a file in following simple and platform independent way: 您可以通过以下简单且与平台无关的方式将JTextArea内容写入文件:

 PrintWriter pw=new PrintWriter("D:/text1.txt");
 textArea.write(pw);
 pw.close();

Hope, this is helpful to you. 希望对您有帮助。

If you are using Windows, then you should do: 如果您使用的是Windows,则应该执行以下操作:

editor.append(line + "\r\n");

Because the new-line in Windows is denoted by \\r\\n , ie, a carriage-return and a line-feed. 因为Windows中的换行用\\r\\n表示,即回车和换行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM