❮ Previous Next ❯

Externalization

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.

❮ Previous Next ❯


  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved