Wednesday, 12 October 2016

Java Tutorial : Java IO (Java Externalizable | Java externalization | Custom Serialization)

🚀 Enjoying Java Tutorials?

Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

🔔 Subscribe to Ram N Java

Introduction to Externalizable

Standard Java serialization via Serializable is automatic, but it writes extra class metadata and persists all non-transient fields by default. When you need complete control over which data members get written and read, or need optimized performance and reduced byte sizes, Java Externalization using the Externalizable interface is the ideal solution.

How Externalization Works

The Externalizable interface extends java.io.Serializable. Unlike default serialization, it shifts the responsibility of serializing and deserializing entirely to the programmer through two explicit methods:

  • writeExternal(ObjectOutput out): Define your custom logic here to write only the essential fields to the output stream.
  • readExternal(ObjectInput in): Restore those fields in the exact order and data types in which they were written.

Important Rules for Externalizable

1. Public No-Argument Constructor

A class implementing Externalizable must have a public no-arg constructor. During deserialization, the JVM calls this constructor first to instantiate the object before invoking readExternal().

2. Transient Modifier is Ignored

Because you explicitly code every read and write operation inside the callback methods, the transient keyword has no impact on externalization.

3. Performance Optimization

By excluding JVM metadata and only streaming the specific attributes you select, externalization significantly reduces network bandwidth and storage overhead.

Related Tutorials from Ram N Java


Click here to watch in Youtube :
https://www.youtube.com/watch?v=OwN-tDEa9V4&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial : Java IO (Java Externalizable | Java externalization | Custom Serialization) 
Java Tutorial : Java IO (Java Externalizable | Java externalization | Custom Serialization) 
Java Tutorial : Java IO (Java Externalizable | Java externalization | Custom Serialization) 
Employee.java
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Employee implements Externalizable
{
    private int id;
    private String name;
    private int age;

    public Employee()
    {

    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    @Override
    public String toString()
    {
        return "Employee [id=" + id + ", name=" + name + 
                ", age=" + age + "]";
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException
    {
        System.out.println("Inside readExternal");
        id = in.readInt();
        name = (String) in.readObject();
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException
    {
        System.out.println("Inside writeExternal");
        out.writeInt(id);
        out.writeObject(name);
    }

}
ExternalizableWrite.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ExternalizableWrite
{

    public static void main(String[] args) throws FileNotFoundException,
            IOException, ClassNotFoundException
    {
        ExternalizableWrite externalizableWrite = new ExternalizableWrite();
        externalizableWrite.writeEmployeeObject();
    }

    private void writeEmployeeObject() throws FileNotFoundException,
            IOException
    {
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        //Serialize
        try
        {
            fileOutputStream = new FileOutputStream("employee.ser");
            objectOutputStream = new ObjectOutputStream(fileOutputStream);

            Employee employee = new Employee();
            employee.setId(101);
            employee.setName("Peter");
            employee.setAge(25);

            System.out.println(employee);

            /*
             * Write the specified object to the
             * ObjectOutputStream.
             */
            objectOutputStream.writeObject(employee);
            System.out
                    .println("Successfully written employee object to the file.\n");
        }
        finally
        {

            if (objectOutputStream != null)
            {
                /*
                 * Closing a ObjectOutputStream will also
                 * close the OutputStream instance to which
                 * the ObjectOutputStream is writing.
                 */
                objectOutputStream.close();
            }
        }

    }

}
Output

Employee [id=101, name=Peter, age=25]
Inside writeExternal
Successfully written employee object to the file.
employee.ser


ExternalizableRead.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ExternalizableRead
{

    public static void main(String[] args) throws FileNotFoundException,
            IOException, ClassNotFoundException
    {
        ExternalizableRead externalizableRead = new ExternalizableRead();
        externalizableRead.readEmployeeObject();
    }

    private void readEmployeeObject() throws IOException,
            FileNotFoundException, ClassNotFoundException
    {
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        //Deserialize 
        try
        {
            fileInputStream = new FileInputStream("employee.ser");
            objectInputStream = new ObjectInputStream(fileInputStream);

            /*
             * Read an object from the ObjectInputStream.
             */
            Employee employee = (Employee) objectInputStream.readObject();
            System.out.println(employee);
            System.out
                    .println("Successfully read employee object from the file.\n");

            System.out.println("Id  = " + employee.getId());
            System.out.println("Name = " + employee.getName());
            System.out.println("Age = " + employee.getAge());

        }
        finally
        {

            if (objectInputStream != null)
            {
                /*
                 * Closing a ObjectInputStream will also
                 * close the InputStream instance from which
                 * the ObjectInputStream is reading.
                 */
                objectInputStream.close();
            }
        }

    }

}
Output
Inside readExternal
Employee [id=101, name=Peter, age=0]
Successfully read employee object from the file.

Id  = 101
Name = Peter
Age = 0

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_Externalizable_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/JavaIODemo_Externalizable_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/9f822df4c81f286daa095d86846058f3a9c16303/BasicJava/JavaIODemo_Externalizable_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment

    Tutorials