Append serializable objects to file

I am trying to save serialized objects to a file but also be able to add new objects and change ones that already exists. the problem i have is i can access the very first object i have saved but the second one is corrupt so im guessing all the others after that will also be corrupt :/.

Error code:
Exception in thread "main" java.io.StreamCorruptedException: invalid type code: AC
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1373)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)
        at TestData.readPersons(TestData.java:76)
        at TestData.main(TestData.java:28)
Java Result: 1

Thanks in advanced.
public void add1() {
        Patient patient;
        ObjectOutputStream out = null;
        try {
            FileOutputStream fos = new FileOutputStream("test.dat", true);
            out = new ObjectOutputStream(fos);
            HealthProblem[] healthproblem = new HealthProblem[1];
            healthproblem[0] = new HealthProblem ("patientHealth", "dateDiagnosed", "problemName", "problemArea", "notes");
            patient = new Patient(1,"Luke Houlahan", "100 Test", "0148471000", healthproblem);
            out.writeObject(patient);
            out.flush();
            out.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void add2() {
        Patient patient;
         ObjectOutputStream out = null;
        try {
            FileOutputStream fos = new FileOutputStream("test.dat", true);
            out = new ObjectOutputStream(fos);
            HealthProblem[] healthproblem = new HealthProblem[1];
            healthproblem[0] = new HealthProblem ("patientHealth1", "dateDiagnosed1", "problemName1", "problemArea1", "notes1");
            patient = new Patient(2,"John", "101 Test", "0148471001", healthproblem);
            out.writeObject(patient);
            out.flush();
            out.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void readPersons() throws IOException {
        Patient result = null;
        FileInputStream in = new FileInputStream("test.dat");
        try {
            ObjectInputStream ois;
            ois = new ObjectInputStream(in);
            while (in != null) {
                result = (Patient) ois.readObject();
                if ("john".equalsIgnoreCase(result.getName())) {
                    System.out.println("Patient Name - " + result.getName());
                    System.out.println("Address - " + result.getAddress());
                    System.out.println("TelNumber - " + result.getTelNumber() + "\n");
                }
            }

            in.close();
        } catch (ClassNotFoundException ex) {
            System.out.println("- [] Class Not Found Error!");
        }
    }

Open in new window

houlahanAsked:
Who is Participating?
 
houlahanConnect With a Mentor Author Commented:
sorry miss read. i abandoned the question as i had decided to use my sql as it was a better option for what i was doing. thanks for all help.
houlahan
0
 
CPColinConnect With a Mentor Senior Java ArchitectCommented:
Hi houlahan,

ObjectOutputStream does not support appending to files by default. This is because the standard implementation writes a header when it is constructed. The way to make an appendable ObjectOutputStream is to extend that class, then override the writeStreamHeader() method to make it do nothing.

When opening the file for writing, you'll have to determine whether or not it's been written to before and use your new appendable ObjectOutputStream instead of a normal ObjectOutputStream in that case. If you're creating a new file, on the other hand, you have to use the standard ObjectOutputStream, so it can write the stream header.
0
 
houlahanAuthor Commented:
Ive seen that when researching appending to file and quite a lot of people don't recommend this. hmm how else could i save my data in a similar way i have tried xml but had no look. i am writing a client server application that needs to be able to pass data back and forth from the server to the client and visa versa. thanks again
0
 
CPColinConnect With a Mentor Senior Java ArchitectCommented:
You could use a DataOutputStream and DataInputStream and write each of your fields by hand. You have to be a little more careful, though, by making sure you read things in the same order that you wrote them and all that.
0
 
CPColinSenior Java ArchitectCommented:
Either comment should have answered the asker's question.
0
All Courses

From novice to tech pro — start learning today.