StreamCorruptedException using readObject()

I wrote a object to .ser file using writeObject().

and then again opened the file for writing in append mode,

and wrote again a object to the .ser file.

now the problem is using readObject() for the first time retrieve the first object added.

but again doing a readObject() does not return the second object added.instead it throws

java.io.StreamCorruptedException.folowing is the sample code

File file =new File("/home/dhans/travelcache/test.ser");

ObjectOutputStream os =new ObjectOutputStream(

new BufferedOutputStream(new FileOutputStream(file)));

HashMap hm =new HashMap();

hm.put("cd","1001");

os.writeObject(hm);

os.flush();

os.close();

ObjectOutputStream os1 =new ObjectOutputStream(

new BufferedOutputStream(new FileOutputStream(file,true)));

// OPENED FILE FOR append mode

HashMap hm1 =new HashMap();

hm1.put("cd1","1002");

os1.writeObject(hm1);

os1.flush();

os1.close();

ObjectInputStream is =new ObjectInputStream(

new BufferedInputStream(new FileInputStream(file)));

HashMap hm2 = (HashMap)is.readObject();

HashMap hm3 = (HashMap)is.readObject();// exception occurs HERE

is.close();

but if i add the two objects at a time like

ObjectOutputStream os =new ObjectOutputStream(

new BufferedOutputStream(new FileOutputStream(file)));

HashMap hm =new HashMap();

hm.put("cd","1001");

os.writeObject(hm);

HashMap hm1 =new HashMap();

hm1.put("cd1","1002");

os.writeObject(hm1);

using the readObject() two times does not throw any exception.

but my requirement is i have to open the file for append mode again to write the second and successive objects .

any help would be helpful.

thanks,

dhanasekaran

[2749 byte] By [dhana007a] at [2007-10-3 2:33:09]
# 1

> I wrote a object to .ser file using writeObject().

> and then again opened the file for writing in append

> mode,

> and wrote again a object to the .ser file.

> now the problem is using readObject() for the first

> time retrieve the first object added.

> but again doing a readObject() does not return the

> second object added.instead it throws

> java.io.StreamCorruptedException

... because you can't do that. Either keep the ObjectOutputStream open and do multiple writes, or write to multiple files. With the buffering that ObjectInputStream does, the third alternative of using multiple ObjectInputStreams, one per object read, might work but is unsafe.

ejpa at 2007-7-14 19:32:08 > top of Java-index,Java Essentials,New To Java...