這是我的代碼..當我按下按鈕時,它只能在文件中寫入一行,但如果再次按下它一組新的字符,它只會刪除舊字符並存儲新的字符集。我不知道如何使它寫字在不同的線路,每次我按下按鈕,而不刪除其他線路如何在每次按「寫入」按鈕時將字符串行寫入文件
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);
}
}
});
}
}
'FileWriter'的構造函數接受第二個參數:'boolean append',您可以使用**追加**而不是覆蓋。基本上,使用'FileWriter作家=新FileWriter(文件,真)' – Aziz 2012-08-13 16:03:25