Saturday, October 31, 2015

Serializing the objects Java

Serialization is quite simple, if we have requirement to Serialize and ArrayList that contains a number of Objects, below are the steps to do

1. Create the object that goes into the array list as Serializable objects
2. Optionally, add a field into the object which can tell the version of the class structure.

Now just add to the array list and serialize the array list, be

public class Accessory implements Serializable

{
    private int type;
    private int state;
    private String name;
    private String uuid;

    public Accessory(int type, int state, String name, String uuid)
    {
        this.type = type;
        this.state = state;
        this.name = name;
        this.uuid = uuid;
    }
}

 public void saveAccessories(ArrayList accessoryList)
    {
        try
        {
            FileOutputStream fos= new FileOutputStream("myfile");
            ObjectOutputStream oos= new ObjectOutputStream(fos);
            oos.writeObject(accessoryList);
            oos.close();
            fos.close();
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
    
    public ArrayList loadAccessories()
    {
        try
        {
            FileInputStream fis = new FileInputStream("myfile");
            ObjectInputStream ois = new ObjectInputStream(fis);
            Object obj = ois.readObject();
            ois.close();
            return (ArrayList)obj;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

References:
http://www.journaldev.com/2452/java-serialization-example-tutorial-serializable-serialversionuid

No comments:

Post a Comment