serializing multiple objects in the same file

Posted on 2010-11-14
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
Question by:hipal
  • 3
LVL 86

Expert Comment

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

Author Comment

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

Accepted Solution

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

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);



	ObjectInputStream ois = new ObjectInputStream(new FileInputStream("x.ser"));

	for(int i = 0;i < 5;i++) {	






Open in new window

LVL 92

Expert Comment

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
LVL 86

Expert Comment

ID: 34134989

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

762 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

21 Experts available now in Live!

Get 1:1 Help Now