How to Efficiently Serialize and Deserialize Arrays in Java?
Last Updated :
25 Jan, 2024
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.
Prerequisites:
Program for Serialize and Deserialize Arrays in Java
Below is the implementation of the Serialize and Deserialize Arrays in Java:
Java
import java.io.*;
public class GFG {
public static void main(String[] args) {
int [] intArray = { 10 , 20 , 30 , 40 , 50 };
try (ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( "array.ser" ))) {
out.writeObject(intArray);
} catch (IOException e) {
e.printStackTrace();
}
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
Explaination of the above Program:
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.
Share your thoughts in the comments
Please Login to comment...