save Object to a file - Android File Input Output

Android examples for File Input Output:Binary File

Description

save Object to a file

Demo Code


import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import android.content.Context;

public class Main {
  public static boolean saveObject(Context context, Object objectToSave, String fileName) {
    final File suspend_f = new File(context.getCacheDir(), fileName);

    FileOutputStream fos = null;/*from  w  ww .j  a  va2  s .  c  om*/
    ObjectOutputStream oos = null;
    boolean keep = true;

    try {
      fos = new FileOutputStream(suspend_f);
      oos = new ObjectOutputStream(fos);
      oos.writeObject(objectToSave);
    } catch (Exception e) {
      keep = false;
      e.printStackTrace();
    } finally {
      try {
        if (oos != null)
          oos.close();
        if (fos != null)
          fos.close();
        if (keep == false)
          suspend_f.delete();
      } catch (Exception e) {

        /* do nothing */
      }
    }

    return keep;
  }

  private static boolean saveObject(String filePath, String fileName, Object objectToSave) {
    final File suspend_f = new File(filePath, fileName);

    FileOutputStream fos = null;
    ObjectOutputStream oos = null;
    boolean keep = true;

    try {
      fos = new FileOutputStream(suspend_f);
      oos = new ObjectOutputStream(fos);
      oos.writeObject(objectToSave);
    } catch (Exception e) {
      keep = false;
    } finally {
      try {
        if (oos != null)
          oos.close();
        if (fos != null)
          fos.close();
        if (keep == false)
          suspend_f.delete();
      } catch (Exception e) { /* do nothing */
      }
    }

    return keep;
  }
}

Related Tutorials