您好,我已经编写了一个应用程序来将 TextArea 中的内容写入文本文档,但问题是,他确实写了它,但它没有存储它,当我再次打开它时,在同一个文本文档中写更多内容(或创建一个新文档)。我怎么能那样做?我需要的一个附加信息是如何在我在文本文档中输入的文本旁边添加日期戳?这是我的代码:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
public class Write extends JFrame {
JTextArea text;
public Write() {
this.setTitle("Writerz!");
setSize(400, 200);
setResizable(false);
setLocation(370, 150);
setLayout(null);
JLabel lbltitlu = new JLabel("Insert your text here");
lbltitlu.setBounds(85, 5, 120, 25);
this.add(lbltitlu);
final JTextArea text = new JTextArea();
text.setSize(199, 199);
text.setBounds(85, 65, 120, 25);
add(text);
JButton btn = new JButton("Add text");
btn.setSize(99, 99);
btn.setBounds(125, 125, 120, 25);
add(btn);
ActionListener listenerbtn = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO auto- generated method
String actionbtn = arg0.getActionCommand();
if (actionbtn.equals("Add text")) {
Adauga(text.getText());
}
}
};
btn.addActionListener(listenerbtn);
}
public void Adauga(String text) {
String filename = "test.txt";
FileWriter writer = null;
try {
writer = new FileWriter(filename);
writer.write(text);
} catch (IOException exception) {
System.err.println("Save oops");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
}
}
谢谢