Let's see an example :
Example
import java.io.*; public class Car implements Externalizable { String name; int year; /* * mandatory public no-arg constructor */ public Car() { super(); } Car(String n, int y) { name = n; year = y; } /** * Mandatory writeExernal method. */ public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(name); out.writeInt(year); } /*** Mandatory readExternal method.*/ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { name = (String) in.readObject(); year = in.readInt(); } /** * Prints out the fields. used for testing!*/ public String toString() { return("Name: " + name + "\n" + "Year: " + year); } }
Example
import java.io.*; public class ExternExample { public static void main(String args[]) { // create a Car object Car car = new Car("Mitsubishi", 2009); Car newCar = null; //serialize the car try { FileOutputStream fo = new FileOutputStream("tmp"); ObjectOutputStream so = new ObjectOutputStream(fo); so.writeObject(car); so.flush(); } catch (Exception e) { System.out.println(e); System.exit(1); } // de-serialize the Car try { FileInputStream fi = new FileInputStream("tmp"); ObjectInputStream si = new ObjectInputStream(fi); newCar = (Car) si.readObject(); } catch (Exception e) { System.out.println(e); System.exit(1); } /* * Print out the original and new car information*/ System.out.println("The original car is "); System.out.println(car); System.out.println("The new car is "); System.out.println(newCar); } }
In this example, class Car implements Externalizable interface which means that car object is ready for serialization. This class have two public methods - "writeExternal" and "readExternal". Unlike Serializable interface which will serialize all the variables in the object with just by implementing the interface, here you have to explicitly mention what fields or variables you want to serialize and the same is done in "writeExternal" and "readExternal" methods. So in the "ExternExample" class, when you write the "Car" object to the OutputStream, the "writeExternal" method is called and the data is persisted. The same applies to "readExternal" method in the Car object i.e., when you read the "Car" object from the ObjectInputStream, "readExternal" method is called.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc