how to deserialize an object from a file that has multiple serialized objs?

In the below program i am serializing multiple objects into a single file & de-serializing all of them.

class ObjectOutputStreamAppendextends ObjectOutputStream

{

ObjectOutputStreamAppend(OutputStream os)throws IOException

{

super(os);

}

@Override

protectedvoid writeStreamHeader()throws IOException

{

reset();

}

publicstaticvoid main(String arg[])throws Exception

{

File f =new File("serial");

f.delete();

FileOutputStream fos =new FileOutputStream(f,true);

ObjectOutputStream oos =new ObjectOutputStream(fos);

oos.writeObject("hello");

oos.writeObject(new Integer(2));

oos.writeObject("world");

oos.writeObject(new Integer(3));

oos.flush();

oos.close();

FileInputStream fis =new FileInputStream(f);

ObjectInputStream ois =new ObjectInputStream(fis);

for (int i=0; i<4; i++)

System.out.println(ois.readObject());

}

}

Output is:

hello

2

world

3

The above program reads all the objects written into the file one by one.

Is there any way to read a particular object randomly? For eg. i want to read only the 3rd object (world)? Is it possible read a particular object?

Thank you.

[2312 byte] By [ksenthilnathanita] at [2007-11-27 2:55:26]
# 1

Object object = ObjectInputStream.readObject();

if(object instanceof X){

do something;

}

if(object instance of Y){

do something;

}

junmina at 2007-7-12 3:32:11 > top of Java-index,Core,Core APIs...
# 2
Thank you for ur response.I forgot to mention that all the objects i serialized into a file are of same type!!!! They all belongs to same class.Can i create my own headers before writing each object? If it is possible i may read an object using that header. Is it possible?
ksenthilnathanita at 2007-7-12 3:32:11 > top of Java-index,Core,Core APIs...
# 3

Yes, just use one of the DataOutputStream methods inherited by ObjectOutputStream. Remember that you have to read them each time:

for (int i = 0; i < N; i++)

{

int h = oin.readInt(); // assuming header is an int

Object o = oin.readObject();

}

ejpa at 2007-7-12 3:32:11 > top of Java-index,Core,Core APIs...