2013年9月29日 星期日

write & read object to file by Serializable


ex:

public class FitPlan implements Serializable {

public long startDateNumber;
public long endDateNumber;
public float targetWeight;
public float startWeight;
public String name;
public int calorieQuota;
public int bmr;
public float workPercentage;
public String uuid;


       public void writeToFile(Context context)
{
File file = new File(context.getFilesDir(), "plan.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);            
oos.writeObject(this);
oos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public static FitPlan createFromFile(Context context)
{
File file = new File(context.getFilesDir(), "plan.txt");
FitPlan plan = null;

try{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fis);            

plan = (FitPlan) in.readObject();

in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return plan;
}

}

說明
FitPlan的每個欄位也都必須是Serializable,才能寫入檔案。
不想寫入檔案的欄位,可加上transient



沒有留言:

張貼留言