Browse - Programming Tips - Java: Serialize an object to a file

Date: 2018oct11
Language: Java
Keywords: serial, serialize, persist, database, POD

Q.  Java: Serialize an object to a file

A.  Use ObjectOutputStream like this.

boolean writeObject(final LinkedList<Entry> list) { final String filename = "myobject.dat"; try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename)); oos.writeObject(list); oos.flush(); oos.close(); } catch(Exception ex) { System.err.println(ex.getMessage()); return false; } return true; }
@SuppressWarnings("unchecked") LinkedList<Entry> readObject() { final String filename = "myobject.dat"; LinkedList<Entry> list = new LinkedList<Entry>(); try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename)); list = (LinkedList<Entry>) ois.readObject(); ois.close(); } catch(Exception ex) { System.err.println(ex.getMessage()); } return list; }
Error checking and file locking omitted for clarity. This works with any kind of object, LinkedList<Entry> is just an example.