Java Serializable example
14 January 2013
In this tutorial you will learn how to serialize a Java object to the file system and read it afterwards.
Introduction
This tutorial will demonstrate how to serialize a Java object to the file system. After serialization we will read it again into memory.
Environment:
- Ubuntu 12.04
- JDK 1.7.0.09
A simple class
Let's define a simple class to use in this example:
User class
package com.byteslounge.serialization; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = -388040256197985515L; private int id; private String username; private String email; public User(int id, String username, String email) { this.id = id; this.username = username; this.email = email; } public int getId() { return id; } public String getUsername() { return username; } public String getEmail() { return email; } }
Note that we are implementing the Serializable interface. This is required to make User class serializable.
Serializing
Serializing a User instance to the file system:
Serializing
User userWrite = new User(1, "johndoe", "John Doe"); FileOutputStream fos = new FileOutputStream("testfile"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(userWrite); oos.flush(); oos.close();
Deserializing
Deserializing a User instance from the file system:
Deserializing
User userRead; FileInputStream fis = new FileInputStream("testfile"); ObjectInputStream ois = new ObjectInputStream(fis); userRead = (User)ois.readObject(); ois.close();
Testing
Let's create a simple test class:
Main.java
package com.byteslounge.serialization; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Main { public static void main(String[] args) throws Exception { User userWrite = new User(1, "johndoe", "John Doe"); FileOutputStream fos = new FileOutputStream("testfile"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(userWrite); oos.flush(); oos.close(); User userRead; FileInputStream fis = new FileInputStream("testfile"); ObjectInputStream ois = new ObjectInputStream(fis); userRead = (User)ois.readObject(); ois.close(); System.out.println("username: " + userRead.getUsername()); } }
When we run the test the following output is generated:
username: johndoe
The example source code is available at the end of this page.
Download source code from this article
Download link: java-serializable-example.zip