Java provides a method of saving objects to file, called Serialization. In order for an object to be serializable it must implement the java.io.Serializable interface and you should set a version ID as well as shown below.
class Student implements java.io.Serializable { String name = ""; Integer age = 0; Double gpa = 0.0; private static final long serialVersionUID = 1L; }
You can save the object to file like this:
try { FileOutputStream fileOut = new FileOutputStream(path); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(obj); } catch (IOException i) { i.printStackTrace(); }
And you can load it like this:
try { FileInputStream fileIn = new FileInputStream(path); ObjectInputStream in = new ObjectInputStream(fileIn); obj = (Student)in.readObject(); } catch (FileNotFoundException fnf) { System.out.println("No serialized file found at " + path + ". Creating new blank object."); obj = new Student(); } catch (Exception e) { e.printStackTrace(); }