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?