Error ObjectInputStream

I use ObjectOutputStream to create a file of serialized objects. Then I use an ObjectInputStream with the readObject () method to return the objects from the file.

It works great for the first time. This means that if the file does not exist, and I open it, then add any number of objects, I can open the ObjectInputStream object and get access to all objects.

However, if I subsequently open the same file (using the append parameter) and add more objects, the ObjectInputStream object will receive java.io.StreamCorruptedException: "invalid type code: AC" error where new objects should start.

Anyone else come across this? I even went back to some basic tutorial examples from Deitel's book and still get the same error.

Edit: I found this - you cannot attach to the end of a serialized stream after closing it and reopening it in add mode. The write will work, but when you go read the file later, you will get a java.io.StreamCorruptedException. at " http://mindprod.com/jgloss/gotchas.html#SERIALIZATION "

+5
source share
3 answers

, . " ", ( ZIP!), . , ObjectInputStream . . , ( ).

ObjectInputStream ObjectOutputStream. , , , Object(In|Out)putStream .

+4

, , .

,

SomeObject[] obj = new SomeObject[numObjects];
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file");
out.writeObject(obj);
out.close();
long ts = System.currentTimeMillis();
ObjectOutputStream tout =
        new ObjectOutputStream(new FileOutputStream("timestamp.obj");
tout.writeObject(new Long(ts));

timestamp.obj , , SomeObject[] .

ObjectInputStream in =
        new ObjectInputStream(new FileInputStream("timestamp.obj"));
Long ts = (Long)in.readObject();

if (ts > prevts) {
    ObjectInputStream in2 = new ObjectInputStream(new FileInputStream("file"));
    SomeObject[] obj = (SomeObject[])in.readObject(); 
    prevts = ts;
}
+1

ObjectStream . , , , .

, ObjectStream. , , , , / .

ObjectStream , / (, / ) ObjectStream .

+1

All Articles