Serialization of Objects in File Operations in Java
Table of Contents
- Introduction
- What is Serialization in Java?
- Step-by-Step Guide to Serialize and Deserialize Objects
- Example Code
- Explanation
- Pros and Cons of Serialization
- Conclusion
Introduction
Serialization is a mechanism in Java that allows converting an object into a byte stream, enabling you to save it to a file or transfer it over a network. This process is crucial when you need to persist data or send objects between different systems. In this guide, we will explore how to serialize and deserialize objects in Java, using file operations, and the benefits and drawbacks of using serialization.
What is Serialization in Java?
Serialization in Java refers to the process of converting an object into a sequence of bytes so that it can be stored in a file or transmitted over a network. Conversely, deserialization is the reverse process, converting the byte stream back into an object. Java provides built-in support for serialization through the Serializable interface.
Key Concepts:
- Serializable Interface: Any object that needs to be serialized must implement the Serializable interface. This interface does not contain any methods, and its purpose is purely to mark a class as serializable.
- ObjectOutputStream: This class is used to serialize an object and write it to a file.
- ObjectInputStream: This class is used to deserialize an object from a file back into memory.
Step-by-Step Guide to Serialize and Deserialize Objects
Example Code for Serialization
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.studyeasy; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class Main { public static int x = 50; public static void main(String[] args) { Vehicle bike = new Vehicle("Bike", 52141); Vehicle car = new Vehicle("Car", 95824); try (FileOutputStream fos = new FileOutputStream("Studyeasy//vehicle.dat")) { try (ObjectOutputStream obj = new ObjectOutputStream(fos)) { // Writing objects to the file obj.writeObject(bike); obj.writeObject(car); System.out.println("Objects have been serialized to vehicle.dat"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
Example Code for Deserialization
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package org.studyeasy; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; public class ReadObject { public static void main(String[] args) { try (FileInputStream fis = new FileInputStream("Studyeasy//vehicle.dat")) { try (ObjectInputStream obj = new ObjectInputStream(fis)) { // Reading objects from the file Vehicle v1 = (Vehicle) obj.readObject(); Vehicle v2 = (Vehicle) obj.readObject(); System.out.println(v1); System.out.println(v2); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } |
Vehicle Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package org.studyeasy; import java.io.Serializable; public class Vehicle implements Serializable { private static final long serialVersionUID = -8948432491824001605 L; private final String type; private final int number; public Vehicle(String type, int number) { this.type = type; this.number = number; } @Override public String toString() { return "Vehicle{" + "type='" + type + '\'' + ", number=" + number + '}'; } } |
Code Explanation
- Serialization (Main.java):
The Vehicle objects are created (a bike and a car) and then written to a file using ObjectOutputStream. This converts the objects into a byte stream and stores them in vehicle.dat. - Deserialization (ReadObject.java):
The Vehicle objects are read back from vehicle.dat using ObjectInputStream. The file is opened, and the objects are deserialized (converted back to their original form) and printed to the console. - Vehicle.java:
This is the class of the object being serialized and deserialized. It implements the Serializable interface, allowing it to be written and read from a file. The class contains attributes and a toString() method to print the object.
Output
1 2 |
Vehicle{type='Bike', number=52141} Vehicle{type='Car', number=95824} |
Pros and Cons of Serialization
Pros | Cons |
---|---|
Allows saving and transferring complex objects | Serialization is language-dependent |
Simple and convenient to use | Can lead to performance overhead |
Built-in support in Java | Any changes in class structure break deserialization |
When to Use Serialization
Persistent Storage: When you want to store the state of an object in a file for later use.
Networking: When you need to send objects over a network.
Avoid using serialization when:
- The data needs to be accessible by different programming languages.
- Performance is a critical concern, as serialization can add overhead.
Conclusion
In this article, we explored the concept of object serialization in Java, demonstrating how to serialize and deserialize objects using file operations. We reviewed the code examples and discussed the pros and cons of using serialization. This powerful feature allows developers to easily persist and transfer objects, making it an essential tool in Java programming.