Serialize an Object to a File in Java
Problem
Serialization turns an object into a stream of bytes that can be saved or sent, and deserialization rebuilds an equivalent object from those bytes.
Save an account object to a file, read it back, and show which fields survive the round trip.
Java Program
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SerializeObjectToFile {
static class Account implements Serializable {
private static final long serialVersionUID = 1L; // version stamp checked when reading back
String owner;
double balance;
transient String sessionToken; // transient: deliberately not saved
Account(String owner, double balance, String sessionToken) {
this.owner = owner;
this.balance = balance;
this.sessionToken = sessionToken;
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Path file = Paths.get("account.ser");
Account original = new Account("Meera", 2500.75, "temp-123");
try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(file))) {
out.writeObject(original); // object -> bytes
}
Account restored;
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(file))) {
restored = (Account) in.readObject(); // bytes -> a new object
}
System.out.println("Owner: " + restored.owner);
System.out.println("Balance: " + restored.balance);
System.out.println("Session token: " + restored.sessionToken);
System.out.println("Same object in memory: " + (original == restored));
Files.delete(file);
}
}Output
Core Logic
A class that implements Serializable can be written with writeObject and recreated with readObject; fields marked transient are left out.
- 1
Account implements Serializableand declares aserialVersionUID. - 2
ObjectOutputStream.writeObjectwrites the object's fields toaccount.ser. - 3
ObjectInputStream.readObjectrebuilds a newAccount, which is cast back to its type. - 4The
transientsession token isn't saved, so it comes back asnull.
Key Point: Changing a class without keeping its serialVersionUID makes old files unreadable with InvalidClassException.
Key Concepts
Approach 2: Serializing a Collection
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SerializeListToFile {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Path file = Paths.get("tasks.ser");
List<String> tasks = new ArrayList<>(Arrays.asList("write tests", "review PR", "deploy"));
try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(file))) {
out.writeObject(tasks); // ArrayList and String are both Serializable
}
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(file))) {
@SuppressWarnings("unchecked")
List<String> loaded = (List<String>) in.readObject();
System.out.println("Loaded " + loaded.size() + " tasks: " + loaded);
}
Files.delete(file);
}
}
Output
Core Logic
Standard collections are serializable too, as long as every element they hold is.
- 1An
ArrayList<String>is written with a singlewriteObjectcall. - 2Reading it back needs a cast from
Object, annotated with@SuppressWarnings("unchecked"). - 3The loaded list has the same three tasks.
Loaded 3 tasks with the original order.Key Point: If any element isn't serializable, writing throws NotSerializableException.
Key Concepts
Interview Questions
Is it safe to deserialize data from an untrusted source?
No. Malicious byte streams can trigger dangerous code during deserialization. Use formats like JSON for external data, or a deserialization filter.
What happens to static fields during serialization?
They aren't saved, because they belong to the class rather than to the object.