Monday, 3 October 2016

Java Tutorial : Java IO (Java ObjectInputStream | Java 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 ObjectInputStream

In Java, deserialization is the process of converting a stream of bytes back into a live object in memory. The core class responsible for this operation is ObjectInputStream from the java.io package. It reconstructs previously serialized objects and primitive data from an underlying input source like a file or a network socket.

How ObjectInputStream Works

ObjectInputStream wraps around an existing input stream (such as FileInputStream) and interprets the binary byte stream according to Java's serialization protocol.

Key Methods

  • readObject(): Reads an object from the input stream. Because it returns a reference of type Object, an explicit cast to the target class type is required:
    Employee emp = (Employee) ois.readObject();
  • Primitive Read Methods: Implements DataInput to read primitive values directly using methods like readInt(), readBoolean(), readDouble(), and readUTF().
  • close(): Closes the stream and releases underlying system resources.

Important Rules for Deserialization

1. Reading Sequence: Data must be read back in the exact same sequence and data type order in which it was written by ObjectOutputStream.

2. Class Availability: The bytecode for the class being deserialized must be available in the classpath; otherwise, a ClassNotFoundException is thrown.

3. Exception Handling: Operations with readObject() require handling both IOException and ClassNotFoundException.

Related Tutorials from Ram N Java


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

Click the below Image to Enlarge
Java Tutorial : Java IO (Java ObjectInputStream | Java Serialization) 
Java Tutorial : Java IO (Java ObjectInputStream | Java Serialization) 
Java Tutorial : Java IO (Java ObjectInputStream | Java Serialization) 
Java Tutorial : Java IO (Java ObjectInputStream | Java Serialization) 
Java Tutorial : Java IO (Java ObjectInputStream | Java Serialization) 
Student.java
import java.io.Serializable;

/*
 * Before you can serialize and de-serialize objects the
 * class of the object must implement java.io.Serializable.
 */
public class Student implements Serializable
{

    private static final long serialVersionUID = -1438960132000208485L;
    private String name;
    private int age;

    public Student(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }

    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 "Student [name=" + name + ", age=" + age + "]";
    }

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

public class ObjectOutputStreamDemo
{

    public static void main(String[] args) throws FileNotFoundException,
            IOException, ClassNotFoundException
    {
        ObjectOutputStreamDemo objectOutputStreamDemo = new ObjectOutputStreamDemo();
        objectOutputStreamDemo.writeStudentObject();
    }

    private void writeStudentObject() throws FileNotFoundException, IOException
    {
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try
        {
            fileOutputStream = new FileOutputStream("student.tmp");
            objectOutputStream = new ObjectOutputStream(fileOutputStream);

            Student student = new Student("Peter", 15);
            System.out.println(student);

            /*
             * Write the specified object to the
             * ObjectOutputStream.
             */
            objectOutputStream.writeObject(student);
            System.out
                    .println("Successfully written student 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
Student [name=Peter, age=15]
Successfully written student object to the file.
student.tmp 

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

public class ObjectInputStreamDemo
{

    public static void main(String[] args) throws FileNotFoundException,
            IOException, ClassNotFoundException
    {
        ObjectInputStreamDemo objectInputStreamDemo = new ObjectInputStreamDemo();
        objectInputStreamDemo.readStudentObject();
    }

    private void readStudentObject() throws IOException, FileNotFoundException,
            ClassNotFoundException
    {
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;

        try
        {
            fileInputStream = new FileInputStream("student.tmp");
            objectInputStream = new ObjectInputStream(fileInputStream);

            /*
             * Read an object from the ObjectInputStream.
             */
            Student student = (Student) objectInputStream.readObject();

            System.out
                    .println("Successfully read student object from the file.");

            System.out.println(student);
            System.out.println("Name = " + student.getName());
            System.out.println("Age  = " + student.getAge());
        }
        finally
        {

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

    }

}
Output
Successfully read student object from the file.
Student [name=Peter, age=15]
Name = Peter
Age  = 15
Refer:
https://docs.oracle.com/javase/8/docs/api/index.html?java/io/ObjectInputStream.html
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_ObjectInputStream_App.zip?attredirects=0&d=1

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/77a722c38e027b0dc283350527400c69b6e8d643/BasicJava/JavaIODemo_ObjectInputStream_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