Java Programs›File Handling›Serialize an Object to a File

Serialize an Object to a File in Java

intermediate·  File Handling  ·  File I/O

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.

Input
Account(Meera, 2500.75, token temp-123)
Output
owner and balance restored, token null

Java Program

Java
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

Owner: Meera Balance: 2500.75 Session token: null Same object in memory: false

Core Logic

A class that implements Serializable can be written with writeObject and recreated with readObject; fields marked transient are left out.

How It Works
  1. 1Account implements Serializable and declares a serialVersionUID.
  2. 2ObjectOutputStream.writeObject writes the object's fields to account.ser.
  3. 3ObjectInputStream.readObject rebuilds a new Account, which is cast back to its type.
  4. 4The transient session token isn't saved, so it comes back as null.
The restored object has the same owner and balance but is a different object in memory.
💡

Key Point: Changing a class without keeping its serialVersionUID makes old files unreadable with InvalidClassException.

Key Concepts

SerializableObjectOutputStreamObjectInputStreamtransientserialVersionUID

Approach 2: Serializing a Collection

Java
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

Loaded 3 tasks: [write tests, review PR, deploy]

Core Logic

Standard collections are serializable too, as long as every element they hold is.

How It Works
  1. 1An ArrayList&lt;String&gt; is written with a single writeObject call.
  2. 2Reading it back needs a cast from Object, annotated with @SuppressWarnings("unchecked").
  3. 3The loaded list has the same three tasks.
The program prints Loaded 3 tasks with the original order.
💡

Key Point: If any element isn't serializable, writing throws NotSerializableException.

Key Concepts

ArrayList serializationunchecked cast

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.

Learn the Concept

Related Programs