Skip to content

Persist your Data with Serialization

Adding persistence to application means storing data so that data persists beyond the lifetime of the application.

The easiest way to achieve this is perhaps to save data to (plain text) files. Let's try that as a way of warming up to Java's syntax! Make a new package, persistence and add the following interface to it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
 * A simple interface for writing object persister.
 * @param <T> base data type.
 */
public interface Persister<T> {
  /**
   * Write out a single object instance to a file.
   * @param item To be stored in a file
   * @throws IOException when something goes wrong with serialization.
   */
  void serialize(T item) throws IOException;

  /**
   * Reading a single object instance from a file.
   * @return the item read from file.
   * @throws IOException when something goes wrong with serialization.
   */
  T deserialize() throws IOException;
}

Serialization

When persisting data, you usually access the data in memory and write it out as a series of bytes to some storage or transmission medium (a file on disk), one after the other. This is called serializing, and the reverse process is deserializing.

Let's now implement Persister for the Course class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class CoursePersister implements Persister<Course> {

  private final static String STORE =  "Store.txt";

  @Override
  public void serialize(Course course) throws IOException {
    FileWriter fw = new FileWriter(STORE);
    BufferedWriter bw = new BufferedWriter(fw);

    bw.write(course.getName());
    bw.newLine();
    bw.write(course.getUrl());
    bw.newLine();

    bw.close();
  }

  @Override
  public Course deserialize() throws IOException {
    FileReader fr = new FileReader(STORE);
    BufferedReader br = new BufferedReader(fr);

    String name = br.readLine();
    String url = br.readLine();

    br.close();

    return new Course(name, url);
  }

}

You can give it a try:

1
2
3
4
5
6
Persister<Course> p = CoursePersister();
Course c1, c2;
c1 = new Course("OOSE", "jhu-oose.com");
p.serialize(c1);
c2 = p.deserialize();
System.out.println(c2);

The output must be Course{name='OOSE', url='jhu-oose.com'}. Moreover, if you open the Store.txt file, it must contain:

1
2
OOSE
jhu-oose.com