Serialization in Java is the process of converting an object into a byte stream, which can then be saved to a file or sent over a network. This is particularly useful for persisting the state of an object or transferring it between different systems.
To demonstrate serialization, we will create a simple Java class, Person
, and serialize an instance of it.
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Next, we will serialize an instance of Person
to a file.
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializeExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
try (FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(person);
System.out.println("Serialized data is saved in person.ser");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Deserialization is the reverse process, where the byte stream is converted back into a Java object. This allows you to retrieve the original object’s state from a stored format.
Now, let’s read the serialized object from the file and deserialize it.
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializeExample {
public static void main(String[] args) {
Person person = null;
try (FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
person = (Person) in.readObject();
System.out.println("Deserialized Person...");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this article, we covered the concepts of serialization and deserialization in Java with clear examples. By understanding these processes, you can effectively manage object state and facilitate data transfer in your applications.