Implement a Key-Value Store Persister

We persisted Author objects by writing/reading their properties one after the other. This approach is prone to error because you must make sure your code matches the persisted format for both reading and writing. If you change the Author class - for example, adding a dateOfBirth field to it - then you may no longer be able to read from old files because some lines could be read into the wrong properties. A potential solution is to save the data as key-value pairs. Java has the Properties class, which you can use to store value strings with associated key strings:

package persistence;
import model.Author;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class PropertyAuthorPersister implements Persister<Author> {
private final static String STORE = "Author_p.txt";
@Override
public void serialize(Author author) throws IOException {
Properties p = new Properties();
p.setProperty("name", author.getName());
p.setProperty("numOfBooks", String.valueOf(author.getNumOfBooks()));
p.setProperty("nationality", author.getNationality());
FileWriter fw = new FileWriter(STORE);
p.store(fw, "comment"); // replace "comment" with any relevant comment!
fw.close();
}
@Override
public Author deserialize() throws IOException {
Properties p = new Properties();
FileReader fr = new FileReader(STORE);
p.load(fr);
fr.close();
String name = p.getProperty("name");
String numOfBooks = p.getProperty("numOfBooks");
String nationality = p.getProperty("nationality");
return new Author(name, Integer.parseInt(numOfBooks), nationality);
}
}

Write and run a little demo for this and check out the text file that stores the Author object.