问题
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.
What am I doing wrong?
回答1:
See 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);
回答2:
You have to declare it:
JTextArea txtArea1 = new JTextArea();
Then, when you save it, save txtArea1.getText();
回答3:
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().
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:
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.
来源:https://stackoverflow.com/questions/14377549/save-text-area-to-file