Monday, September 16, 2013

Write and Read (Serialize) Object to memory

If you want to save object like HashMap, Array and so on to application memory,
use code below. Please note, all objects fields should be Serializable.

Types like String, int, HashMap... are already serializable, but if you create a class of your own, you should verify that that it implements Serializable, and so all of his content recursively.

Write to file:
    /**
     * Writes Serializable object into a file
     */
    public static void writeObjectToFile(Context context, Object object, String filename)
    {
        ObjectOutputStream objectOut = null;
        try
        {
            FileOutputStream fileOut = context.openFileOutput(filename,Activity.MODE_PRIVATE);
            objectOut = new ObjectOutputStream(fileOut);
            objectOut.writeObject(object);
            fileOut.getFD().sync();

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (objectOut != null)
            {
                try
                {
                    objectOut.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
 
 
Read from file:
    /**
     * Reads a Serializable object from a file
     */
    public static Object readObjectFromFile(Context context, String filename)
    {
        ObjectInputStream objectIn = null;
        Object object = null;
        try
        {
            FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
            objectIn = new ObjectInputStream(fileIn);
            object = objectIn.readObject();

        }
        catch (FileNotFoundException e)
        {
            // Do nothing
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (objectIn != null)
            {
                try
                {
                    objectIn.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

        return object;
    }

No comments:

Post a Comment