java 将文本区域保存到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14377549/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:04:03  来源:igfitidea点击:

Save text area to file

javafile-iotextareasave

提问by Andrew Thompson

Is It possible to save a textarea to a file?

是否可以将文本区域保存到文件?

FileWriter fw = new FileWriter(file1.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(txtArea1);

I get:

我得到:

txtArea1 cannot be resolved to a variable.

txtArea1 无法解析为变量。

What am I doing wrong?

我究竟做错了什么?

回答by Andrew Thompson

See JTextComponent.write(Writer).

JTextComponent.write(Writer)

Stores the contents of the model into the given stream. By default this will store the model as plain text.

将模型的内容存储到给定的流中。默认情况下,这会将模型存储为纯文本。

Thus, your example might look something like:

因此,您的示例可能类似于:

FileWriter fw = new FileWriter(file1.getAbsoluteFile(), true);
txtArea1.write(fw);

回答by Dan D.

You have to declare it:

你必须声明它:

JTextArea txtArea1 = new JTextArea();

Then, when you save it, save txtArea1.getText();

然后,当你保存它时,保存 txtArea1.getText();

回答by Audrius Meskauskas

I see only very few reasons to save a plain text GUI component to a file. If you only need to save the content, it is better to store the content string that can be obtained through getText().

我认为将纯文本 GUI 组件保存到文件的理由很少。如果只需要保存内容,最好将可以通过getText().

However it may be that you need to store some settings that can be done on JTextArea(tab size, etc). For that, I would propose to use XMLEncoder:

但是,您可能需要存储一些可以完成的设置JTextArea(标签大小等)。为此,我建议使用XMLEncoder

   XMLEncoder e = new XMLEncoder(
                      new BufferedOutputStream(
                          new FileOutputStream("save.xml")));
   e.writeObject(txtArea1));
   e.close();

This will save all non default settings as well as the content string. It is also possible with serialization but this format is less portable between different virtual machines.

这将保存所有非默认设置以及内容字符串。序列化也是可能的,但这种格式在不同虚拟机之间的可移植性较差。