Pages

Tuesday, August 21, 2012

serialize and deserialize an object with java

We usually use serialization, when we need to store an object with the state to a storage medium so that we can use it later or when we need to transfer an object through the network.
Now lets see how to serialize an object to a file.


ObjectOutputStream o = new ObjectOutputStream(new             FileOutputStream("file.ser"));//saving to a file named file.ser
o.writeObject(ObjectToSerialize);//writing the object
o.close();

Now lets see how to deserialize the saved object.


        FileInputStream fileIn =
                          new FileInputStream("file.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
        try {
            dictionaryMap = (ObjectType) in.readObject();//add cast
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Dictionary.class.getName()).log(Level.SEVERE, null, ex);
        }
            in.close();
            fileIn.close();

No comments:

Post a Comment