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?

5

2 Answers 2

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);
        }
0
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.