Dave's Brain

Browse - Programming Tips - How can I quickly save a data structure to disk?

Date: 2015mar30
Language: Java

Q.  How can I quickly save a data structure to disk?

A.  Use Java serialization, like this:

// Make sure your classes implement java.io.Serializable class Entry implements Serializable { String mydata; } String FILENAME = "/tmp/stuff.dat"; boolean writeStuff(ArrayList<Entry> list) { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILENAME)); oos.writeObject(list); oos.flush(); oos.close(); } catch(Exception ex) { System.out.println("Could not write stuff because " + ex.toString()); return false; } return true; } @SuppressWarnings("unchecked") ArrayList<Entry> readStuff() { ArrayList<Entry> list = new ArrayList<Entry>(); try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILENAME)); list = (ArrayList<Entry>) ois.readObject(); ois.close(); } catch(Exception ex) { System.out.println("Could not read stuff because " + ex.toString()); } return list; }

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.