Serialization
Serialization in Java is a mechanism of writing the state of an object into a byte stream. This tutorial will teach you how to serialize and deserialize objects.
Serializing an Object
To serialize an object, use the ObjectOutputStream
class:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Deserializing an Object
To deserialize an object, use the ObjectInputStream
class:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Main {
public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
Person person = (Person) ois.readObject();
System.out.println("Name: " + person.name);
System.out.println("Age: " + person.age);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Transient Keyword
The transient
keyword in Java is used to indicate that a field should not be serialized:
class Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
transient int age; // This field will not be serialized
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
In this example, the age
field will not be serialized because it is marked as transient
.
Continue exploring our intermediate tutorials to learn more about Java programming.