Monday, 17 June 2019

Serialization | Externalizable Interface

java.io.Externalizable interface

There are two methods readExternal() and writeExternal() in Externalizable interface those can be used in the serialization process.

void writeExternal(ObjectOutput out) throws IOException;
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

Externalizable interface extends Serializable interface.

public interface Externalizable extends java.io.Serializable

Need of Externalizable
  • If you are not happy with the way java writes/reads objects from stream.
  • Special handling for supertypes on object construction during serialization.


 Example of Externalizable

Person.java
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Person implements Externalizable {

    private int id;
    private String name;
    private String gender;

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(id);
        out.writeObject(name + "xyz");
        out.writeObject("abc" + gender);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
       
        id = in.readInt();
       
        //read in the same order as written
        name = (String) in.readObject();
        if (!name.endsWith("xyz")) {
            throw new IOException("corrupted data");
        } else {
            name = name.substring(0, name.length() - 3);
        }
        gender = (String) in.readObject();
        if (!gender.startsWith("abc")) {
            throw new IOException("corrupted data");
        } else {
            gender = gender.substring(3);
        }
    }

    @Override
    public String toString() {
        return "Person [id=" + id + " | name=" + name + " | gender=" + gender + "]";
    }

    // Setter methods
}

ExternalizationTest.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ExternalizationTest {

    /**
     * Method to return the Person object instance.
     *
     * @return person object.
     */
    private static Person createObject() {
        Person person = new Person();
        person.setId(1);
        person.setName("Pankaj");
        person.setGender("Male");
        return person;
    }

    /**
     * This method read data from a resource file and deserialize to Java object.
     *
     * @param fileName
     * @param p
     * @return
     */
    private static Person deserializeObjectUtil(String fileName) {
        Person p = null;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {

            p = (Person) ois.readObject();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return p;
    }

    /**
     * Method to store the serialized object to the resource file.
     *
     * @param fileName
     * @param person
     */
    private static void seriliazeObjectUtil(String fileName, Person person) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {

            oos.writeObject(person);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        String fileName = "person.ser";

        // Create person object.
        Person person = createObject();

        // serialize and store the person object instance in file.
        seriliazeObjectUtil(fileName, person);

        // deserialize person object instance from file.
        Person p = deserializeObjectUtil(fileName);

        System.out.println("Person Object Read= " + p);
    }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...