serialization

Given the following class:

Sample Class:House.java

import java.util.*;

publicclass House{

private String name;

private String comments;

private ArrayList residentList =new ArrayList();

publicvoid addResident(Resident resident){

this.residentList.add(resident);

}

publicboolean removeResident(Resident resident){

return this.residentList.remove(resident);

}

publicvoid setResidentList(ArrayList residentList){

this.residentList = residentList;

}

public String setComment (String c){

c = setComment;

return c;

}

public List getHouseList(){

return residentList;

}

public String toString (){

return name.toString();

}

}

Other classes are very much in the same shape,Resident.java, Street.java. which classes have further attributes and methods.

I would like to know how to Serialize the files into a single binary file. Also, how can i retrieve back all such data at once; due to the fact the from House.java, there are methods to call a list of Residents.

Thanks alot for your kind support.

[2219 byte] By [JZazabazullaa] at [2007-11-27 0:26:47]
# 1

All ur classes must implement Serializable interface.

You need to use ObjectOutputStream for writing objects and ObjectInputStream for reading objects.

Serialization: http://www.deitel.com/articles/java_tutorials/20050923/IntroductionToObjectSerialization.html

ObjectOutputStream: http://java.sun.com/javase/6/docs/api/java/io/ObjectOutputStream.html

ObjectInputStream: http://java.sun.com/javase/6/docs/api/java/io/ObjectInputStream.html

chasana at 2007-7-11 22:25:45 > top of Java-index,Java Essentials,New To Java...
# 2
can anyone post a sample code pls?
JZazabazullaa at 2007-7-11 22:25:45 > top of Java-index,Java Essentials,New To Java...
# 3

you can just declair it Serializable and it will work. However, if you ever change the class at all in the future, it will no longer be compatable with old version.

Otherwise, you have to implement:

private void writeObject(java.io.ObjectOutputStream out)

throws IOException

private void readObject(java.io.ObjectInputStream in)

throws IOException, ClassNotFoundException;

and your version number for this class should be stored in

private static final long serialVersionUID

robtafta at 2007-7-11 22:25:45 > top of Java-index,Java Essentials,New To Java...