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?
>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.