Solved

serializing multiple objects in the same file

Posted on 2010-11-14
5
471 Views
Last Modified: 2012-06-21
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
Comment
Question by:hipal
  • 3
5 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 34132761
Just call oos.writeObject several times with the corresponding ois.readObject
0
 

Author Comment

by:hipal
ID: 34132771
so what if I want to read 4th object that I wrote ?
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 34132787
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
 
LVL 92

Expert Comment

by:objects
ID: 34132790
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 34134989
:)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
eclipse java  build path 6 44
How to remove numeric and alpha from an alphanumeric field? 5 72
java stored proc example 9 22
servlet filter example 37 43
A short article about a problem I had getting the GPS LocationListener working.
This is an explanation of a simple data model to help parse a JSON feed
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now