Implement a Key-Value Store Persister¶
We persisted Course
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 Course
class - for example, adding an instructor
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:
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 | public class PropertyCoursePersister implements Persister<Course>{ private final static String STORE = "Store.txt"; @Override public void serialize(Course course) throws IOException { Properties p = new Properties(); p.setProperty("name", course.getName()); p.setProperty("url", course.getUrl()); FileWriter fw = new FileWriter(STORE); p.store(fw, "comment"); // replace "comment" with any relevant comment! fw.close(); } @Override public Course deserialize() throws IOException { Properties p = new Properties(); FileReader fr = new FileReader(STORE); p.load(fr); fr.close(); String name = p.getProperty("name"); String url = p.getProperty("url"); return new Course(name, url); } } |
Write and run a little demo for this and check out the text file that stores the Course
object.