Persist data with serialization

Adding persistence to application means storing data so that data persists beyond the lifetime of the application execution. Typically, for this to happen, we need to to write (i.e. store) data in a non-volatile storage.

The easiest way to go 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:

/**
* 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 a "persister" for the Author class:

package persistence;
import model.Author;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class AuthorPersister implements Persister<Author> {
private final static String STORE = "Author.txt";
public void serialize(Author author) throws IOException {
FileWriter fw = new FileWriter(STORE);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(author.getName());
bw.newLine();
bw.write(author.getNumOfBooks());
bw.newLine();
bw.write(author.getNationality());
bw.newLine();
bw.close();
}
public Author deserialize() throws IOException {
FileReader fr = new FileReader(STORE);
BufferedReader br = new BufferedReader(fr);
String name = br.readLine();
int numOfBooks = Integer.parseInt(br.readLine());
String nationality = br.readLine();
return new Author(name, numOfBooks, nationality);
}
}

You can give it a try:

Persister<Author> p = AuthorPersister();
Author a1, a2;
a1 = new Author("J.D Salinger", 8, "American");
p.serialize(a1);
a2 = p.deserialize();
System.out.println(a2);

The output must be

Author{name='J.D Salinger', numOfBooks=8, nationality='American'}

Moreover, if you open the Author.txt file, it must contain:

J.D Salinger
8
American