这是我的代码。当我按下按钮时,它只能在文件中写入一行,但是,如果我用一组新字符再次按下它,它只会删除旧字符并存储新的字符集。我不知道如何让它在每次按下按钮时在不同的行中写入字符而不删除其他行
package datasaving;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.*;
public class Datasaving {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
final JTextField input = new javax.swing.JTextField(20);
JButton save = new javax.swing.JButton("Write");
frame.add(panel);
frame.setSize(200,200);
panel.add(input);
panel.add(save);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file)) {
writer.write(input.getText()+"\n");
}
System.out.println("Game saved");
} catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
});
}
}