Tuesday, 4 October 2016

Java Tutorial : Java IO (Java Serialization with array or collection)

🚀 Enjoying Java Tutorials?

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

🔔 Subscribe to Ram N Java

Introduction

In real-world Java applications, data is rarely stored in isolated single objects. Most often, you work with data structures like arrays or Java Collections (such as ArrayList, HashSet, or HashMap). Understanding how serialization works when dealing with arrays and collections is essential for persisting structured data efficiently.

Serializing Arrays in Java

In Java, an array is an object. Arrays automatically implement the java.io.Serializable interface under one key condition:

  • Primitive Arrays: Arrays of primitive data types (like int[], char[], double[]) are always serializable by default.
  • Object Arrays: For an array of objects (like Employee[] or String[]), every element stored in the array must implement Serializable. If any object element is not serializable, the JVM will throw a runtime NotSerializableException.

Serializing Collections Framework Classes

Standard Collection classes in the java.util package—such as ArrayList, LinkedList, HashSet, and HashMap—already implement the Serializable interface.

The Element Serializability Rule

Even though the collection object itself implements Serializable, all individual elements contained within the collection must also be serializable.

For example, if you create an ArrayList<Student>, the collection can only be written to an ObjectOutputStream if the Student class explicitly implements Serializable.

Key Takeaways

Type Serializability Rule
Primitive Array Always serializable by default
Object Array Serializable only if all member elements implement Serializable
Java Collections Collection classes implement Serializable, but all contained items must also be serializable

Related Tutorials from Ram N Java


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

Click the below Image to Enlarge
Java Tutorial : Java IO (Java Serialization with array or collection) 
Employee.java
import java.io.Serializable;

public class Employee implements Serializable
{
    private static final long serialVersionUID = 765764534241652904L;
    private int id;
    private String name;

    public Employee(int id, String name)
    {
        super();
        this.id = id;
        this.name = name;
    }

    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;
    }

}
SerializationDemo.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class SerializationDemo
{

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

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

            Employee employee1 = new Employee(101, "Peter");
            Employee employee2 = new Employee(102, "Dave");
            Employee employee3 = new Employee(103, "Ram");

            ArrayList<Employee> listOfEmployees = new ArrayList<Employee>();
            listOfEmployees.add(employee1);
            listOfEmployees.add(employee2);
            listOfEmployees.add(employee3);

            /*
             * Write the specified object to the
             * ObjectOutputStream.
             */
            objectOutputStream.writeObject(listOfEmployees);
            System.out
                    .println("Successfully written list of employee objects 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
Successfully written list of employee objects to the file.
employee.tmp

DeSerializationDemo.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class DeSerializationDemo
{

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

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

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

            /*
             * Read an object from the ObjectInputStream.
             */
            ArrayList<Employee> listOfEmployees = (ArrayList<Employee>) objectInputStream
                                                                            .readObject();
            System.out
                    .println("Successfully read list of employee objects from the file.\n");

            for (Employee employee : listOfEmployees)
            {
                System.out.println("Id  = " + employee.getId());
                System.out.println("Name = " + employee.getName());
                System.out.println("--------------------------");
            }

        }
        finally
        {

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

    }

}
Output
Successfully read list of employee objects from the file.

Id  = 101
Name = Peter
--------------------------
Id  = 102
Name = Dave
--------------------------
Id  = 103
Name = Ram
--------------------------

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/9ef303db3f229fc70e7cf47baac5692282611e62/BasicJava/JavaIODemo_Serialization_Collection_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