Java I/O

Object Serialization

//To write
FileOutputSream fos = new FileOutputStream("object.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);

//YourClass is serializable
YourClass yc = new YourClass();
oos.writeObject(yc);

//To read.
FileInputStream fis = new FileInputStream ("object.dat");
ObjectInputStream ois = new ObjectInputStream (fis);
YourClass yc;
yc = (YourClass) ois.readObject();


//You can also check the type of the object before casting it.
FileInputStream fis = FileinputStream("object.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object object;
object = ois.readObject();
if (object instanceof YourClass)
{
  YourClass yc = object;
  // Perform operations with yc;
}
else if (object instance of AnotherClass)
{
  AnotherClass ac = object;
  // Perform operations with ac
}   


José M. Vidal .

12 of 13