Getting and Saving Objects from/to files in app data folder:

Get Object from file

public static Object getObjectFromFile(Context context, String filename) {

    try {      
        FileInputStream fis = context.openFileInput(filename);
        ObjectInputStream ois = new ObjectInputStream(fis);
        
        Object object = ois.readObject();
        ois.close();
  
        return object;

    } catch (FileNotFoundException e) {
        Log.e(LOG_TAG, "getObjectFromFile FileNotFoundException: " + e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e(LOG_TAG, "getObjectFromFile IOException: " + e.getMessage());
        return null;
    } catch (ClassNotFoundException e) {
        Log.e(LOG_TAG, "getObjectFromFile ClassNotFoundException: " + e.getMessage());
        return null;       
    } catch (Exception e) {// Catch exception if any
        Log.e(LOG_TAG, "getBookmarksFromFile Exception: " + e.getMessage());
        return null;
    }
}

 

Save Object to file

public static void saveObjectToFile(Context context, String fileName, Object obj) {
    
    try {
        FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        
        oos.writeObject(obj); 
        oos.close();

    } catch (FileNotFoundException e) {
        Log.e(LOG_TAG, "saveObjectToFile FileNotFoundException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(LOG_TAG, "saveObjectToFile IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(LOG_TAG, "saveObjectToFile Exception: " + e.getMessage());
    }
}