Java Serialization Example

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();
        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s