Open In App

How to Efficiently Serialize and Deserialize Arrays in Java?

Last Updated : 23 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Serialization is the process of converting an object into a byte stream and deserialization is the process of reconstructing the object from that byte stream. When working with the Arrays in Java, efficiently Serializing and Deserializing them is essential for data storage and transfer.

Serialize and Deserialize Arrays

We will implement the Program into two parts:

  • Serialize: Writes the array length first, followed by each element in the array.
  • Deserialize: Reads the array length, creates a new array, and reads each element into the array.
Java
import java.io.*;

// Driver Class
public class GFG {
      // Main Function
    public static void main(String[] args) {
        int[] intArray = {10, 20, 30, 40, 50};
        
          // Serialization
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("array.ser"))) {
            out.writeObject(intArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
      
      
        // Deserialization
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("array.ser"))) {
            int[] deserializedArray = (int[]) in.readObject();
            for (int num : deserializedArray) {
                System.out.print(num + " ");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Output :

10 20 30 40 50

The Program is divided into two parts Serialization and Deserialization.

Sertialization:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("array.ser"))

Here the created byte stream is stored in out variable is intialised with "array.ser" being the file where array is written. Then next step is ,

out.writeObject(intArray);

Here the "array.ser" is filled with the content of intArray.

Deserialization:

ObjectInputStream in = new ObjectInputStream(new FileInputStream("array.ser"))

Here in is used to read "array.ser". After which,

int[] deserializedArray = (int[]) in.readObject();

It is just extracting data from file and then filling the array elements.


Next Article
Practice Tags :

Similar Reads