Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 480
  • Last Modified:

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
0
hipal
Asked:
hipal
  • 3
1 Solution
 
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
 
CEHJCommented:
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
 
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now