0

I have written multiple objects in the same file over last 2 weeks. Each time (probably million times) I called:

try(ObjectOutputStream output=new ObjectOutputStream(new FileOutputStream(new File("somefile"),true))) {            
        output.writeObject(someobject);               
        output.close();
    } 

Now when I try to read it using:

try(ObjectInputStream input=new ObjectInputStream(new FileInputStream(new File("somefile")))) {   
        while(true) {     
            PROCESS_IT(input.readObject());
        }
    }

It reads only first object and gives error:

java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1379)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)

I know now that I should have overridden the streamheader while writing these objects (Appending to an ObjectOutputStream)

But it took me two weeks already to get the results in this "somefile". Can I somehow still read all the objects by skipping the corrupt bytes/headers? Please advise. Thanks

Community
  • 1
  • 1
Kaur
  • 279
  • 1
  • 6
  • 18

1 Answers1

0

I have not (yet) tested it, but you should be able to recreate the ObjectInputStream each time on the same FileInputStream and it wil re-read the header.

For example (again, untested) :

FileInputStream fis = new FileInputStream("someFile");
while (true) {
  ObjectInputStream input = new ObjectInputStream(fis)
  try {
    PROCESS_IT(input.readObject());
  }
  // Don't close the DataInputStream, it would close the underlying FileInputStream
}

The theory should be that when you create the ObjectInputStream, it will read the header, and then read an object, advancing the underlying FileInputStream. Then, when you iterate and create a second ObjectInputStream, it has no knowledge that the underlying FileInputStream was already partially consumed, so will re-read the header and read another object. And so on.

Simone Gianni
  • 11,426
  • 40
  • 49
  • I tested. But still it reads only first object and gives " java.io.IOException: Stream Closed" error few times. – Kaur Sep 22 '14 at 11:04
  • You might have to not close the `ObjectInputStream`. – user253751 Sep 22 '14 at 11:07
  • No. That definitely won't work. The `try` will close `input` which will close `fis`. – Stephen C Sep 22 '14 at 11:09
  • Yes, now I tried without using "try" statement and seems to be working. Thanks a tons. Saved me from extra hassle. – Kaur Sep 22 '14 at 11:10
  • Oh yes, I forgot the try->close->close thing, that's why I specified the code was untested but only to give an idea of how it could work. Now modified the answer to specify that the ObjectInputStream must not be closed. – Simone Gianni Sep 22 '14 at 13:20