This is my code.. It can only write a line in a file when I press the button but, If I press It again with a new set of Characters, it only delete the old ones and store the new set of char. I don't know how to make it write Characters in a different lines everytime I press the button without deleting the other lines
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);
}
}
});
}
}
Wow, thats a lot happening in one statement. Not my favorite way to handle that, but that wasn't your question.. :-) When you create a new FileWriter it creates a new file so you only see one line of text ever..
Look at the API - there's a constructor for FileWriter which takes in a boolean for whether to append or not.. You want to use that instead.
Another option is to open the file once, and then just write to it each press.. If you want the file opened/closed on each write, then using the other ctor is the better way.