ObjectInputStream, ObjectOutputStream and java.io.Serializable : ObjectInputStream « File Input Output « Java






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

1.Create ObjectInputStream out of FileInputStreamCreate ObjectInputStream out of FileInputStream
2.new ObjectInputStream(new BufferedInputStream(new FileInputStream(StringFileName)));
3.Reading objects from file using ObjectInputStream
4.Read different data types from ObjectInputStream
5.Object serialization with Serializable interface, ObjectOutputStream and ObjectInputStream.
6.Store objects in file
7.Use ObjectOutputStream and ObjectInputStream to write and read Hashtable
8.ObjectStream Test with hierarchy