Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ObjectOutputStream writes same instances differently depending on how i open stream

For the unknown reason, instances written into the same objectOutputStream and instances written separately (If I open objectOutputStream on each iteration) both create two different files.

ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filepath1));
for (User user : users)
{
    objectOutputStream.writeObject(user);
}

objectOutputStream.close();

for (User user : users)
{
    objectOutputStream = new ObjectOutputStream(new FileOutputStream(filepath2, true));
    objectOutputStream.writeObject(user);
    objectOutputStream.close();
}

So when I read files in a loop like this it works fine only for the first file.

for( int i = 0; i< users.length; i++)
{
    readUsers[i] = (User)objectInputStream.readObject();
}

Reading the second file gives me ONE correctly read user which is followed by an Exception java.io.StreamCorruptedException: invalid type code: AC.
I’ve inspected the content of these files and it seems there’s an excessive data at the start of each record in the second one (It takes almost twice as much space as the first one).
So how to combine second way of writing instances to file and read them in a simple loop afterwards?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t write the data from two different ObjectOutputStreams into the same file.

Meaning:

  • either you have to write to different files OR
  • you use the same ObjectOutputStream to write all your objects into that single file.

This is binary data structure that has an implicit layout, the corresponding protocol simply doesn’t expect that another serialized byte stream shows up in a file after a first sequence of objects has been processed completely.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading