ObjectInputStream, ObjectOutputStream and java.io.Serializable
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Engine implements Serializable {
private int numCylinders;
Engine(int numCylinders) {
this.numCylinders = numCylinders;
}
int getNumCylinders() {
return numCylinders;
}
}
class Car implements Serializable {
private int numTires;
private Engine e;
private String name;
Car(String name, int numTires, Engine e) {
this.name = name;
this.numTires = numTires;
this.e = e;
}
int getNumTires() {
return numTires;
}
Engine getEngine() {
return e;
}
String getName() {
return name;
}
}
class Main {
public static void main(String[] args) throws Exception {
Car c1 = new Car("Some car", 4, new Engine(6));
ObjectOutputStream oos = null;
FileOutputStream fos = new FileOutputStream("car.ser");
oos = new ObjectOutputStream(fos);
oos.writeObject(c1);
ObjectInputStream ois = null;
FileInputStream fis = new FileInputStream("car.ser");
ois = new ObjectInputStream(fis);
Car c2 = (Car) ois.readObject();
System.out.println("Number of tires = " + c2.getNumTires());
System.out.println("Number of cylinders = " + c2.getEngine().getNumCylinders());
System.out.println("Name = " + c2.getName());
}
}
Related examples in the same category