0
private void saveFormActionPerformed(java.awt.event.ActionEvent evt) {
    name = nameFormText.getText();
    surname = surnameFormText.getText();
    age = Integer.parseInt(ageFormText.getText());
    stadium = stadiumFormText.getText();

    Venues fix = new Venues();
    fix.setName(name);
    fix.setSurname(surname);
    fix.setAge(age);
    fix.setStadium(stadium);

    File outFile;
    FileOutputStream fStream;
    ObjectOutputStream oStream;

    try {
        outFile = new File("output.data");
        fStream = new FileOutputStream(outFile);
        oStream = new ObjectOutputStream(fStream);
        oStream.writeObject(fix);
        JOptionPane.showMessageDialog(null, "File written successfully");
        oStream.close();
    } catch (IOException e) {
        System.out.println(e);
    }
 }   

This is what I have so far. Any ideas on what I could do with it to append the file if it's already created?

jaredk
  • 986
  • 5
  • 21
  • 37
Karl Rez
  • 15
  • 3
  • Read [How do I check if a file exists? (Java on Windows)](http://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-java-on-windows) – Braj Apr 06 '14 at 14:07
  • Read [How to append text to an existing file in Java](http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – Braj Apr 06 '14 at 14:08
  • @Braj He is using an ObjectOutputStream which doesn't implements the Appendable interface. – Naili Apr 06 '14 at 14:21
  • If OP wants to do then there are lots of ways but OP is looking just for ready made code. – Braj Apr 06 '14 at 14:24
  • Thanks @Braj i had already checked out the second link but it wasnt exactly what i needed. Naili seems to have sorted my problem. – Karl Rez Apr 06 '14 at 14:28

2 Answers2

2

You have first to check if the file exists before, if not create a new one. To learn how to append object to objectstream take a look at this question.

        File outFile = new File("output.data");
        FileOutputStream fStream;
        ObjectOutputStream oStream;
        try {
            if(!outFile.exists()) outFile.createNewFile();
            fStream = new FileOutputStream(outFile);
            oStream = new ObjectOutputStream(fStream);
            oStream.writeObject(fix);
            JOptionPane.showMessageDialog(null, "File written successfully");
            oStream.close();
        } catch (IOException e) {
            System.out.println(e);
        }
Community
  • 1
  • 1
Naili
  • 1,564
  • 3
  • 20
  • 27
2

Using Java 7, it is simple:

final Path path = Paths.get("output.data");
try (
    final OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE,
        StandardOpenOption.APPEND);
    final ObjectOutputStream objOut = new ObjectOutputStream(out);
) {
    // work here
} catch (IOException e) {
    // handle exception here
}

Drop File!

fge
  • 119,121
  • 33
  • 254
  • 329