serializing multiple objects in the same file

Thanks experts for extended support..

Can some one please give a simple example of serializing multiple objects in the same file and deserializing them
hipalAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
You need to read them in order. Or serialize a List and then you can access by index
import java.io.*;
public class WriteRead {
    public static void main(String[] args) throws Exception {
	ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("x.ser"));
	for(int i = 0;i < 5;i++) {	
	    oos.writeObject("" + i);
	}
	oos.close();
	ObjectInputStream ois = new ObjectInputStream(new FileInputStream("x.ser"));
	for(int i = 0;i < 5;i++) {	
	    System.out.println(ois.readObject());
	}
	ois.close();
    }
}

Open in new window

0
 
CEHJCommented:
Just call oos.writeObject several times with the corresponding ois.readObject
0
 
hipalAuthor Commented:
so what if I want to read 4th object that I wrote ?
0
 
objectsCommented:
add them to a ArrayList (or array) and then serialize/deserialize the list/array
that will handle reading/writing all objects in one call
0
 
CEHJCommented:
:)
0
All Courses

From novice to tech pro — start learning today.