将序列化对象保存在手机记忆库中

时间:2013-05-21 09:08:34

标签: android

这里我有一些数据,我想存储在手机内存中并在必要时检索

这是代码:

 public void saveObject(Person p){
     try
     {

         FileOutputStream fos = openFileOutput("save_object.bin", Context.MODE_PRIVATE);
         ObjectOutputStream oos = new ObjectOutputStream(fos);


        oos.writeObject(p); // write the class as an 'object'
        oos.flush(); // flush the stream to insure all of the information was written to 'save_object.bin'
        oos.close();// close the stream
     }
     catch(Exception ex)
     {
        Log.v("Serialization Save Error : ",ex.getMessage());
        ex.printStackTrace();
     }
}

public Object loadSerializedObject(File f)
{
    try
    {
         FileInputStream fin = openFileInput("save_object.bin");

        Object o = fin.read();
        return o;

    }
    catch(Exception ex)
    {
    Log.v("Serialization Read Error : ",ex.getMessage());
        ex.printStackTrace();
    }
    return null;
}

使用sdcard我也收到错误/mnt/sdcard/save_object.bin (Permission denied)

通过

检索
Person person1 = (Person)loadSerializedObject(getDir("save_object.bin",Context.MODE_PRIVATE));//get the serialized object from the sdcard and caste it into the Person class.

类:

public class Person implements Serializable 
{
    String username="";
    private static final long serialVersionUID = 46543445; 

    public void setusername(String username)
    {
        this.username = username;
    }





    public String getusername()
    {
        return username;
    }



}

我用过

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我怎么能把它存放在手机记忆中@Could有人帮助我@Thanks

1 个答案:

答案 0 :(得分:0)

由于您没有有效的挂载点/sdcard,您必须使用应用程序缓存来存储您的对象。

以这种方式检索InputStream:

FileInputStream fin = openFileInput("save_object.bin");
以这种方式

和你的FileOutputStream:

 FileOutputStream fos = openFileOutput("save_object.bin", Context.MODE_PRIVATE);

反序列化对象以这种方式更改代码:

FileInputStream fin = openFileInput("save_object.bin");
 ObjectInputStream ois = new ObjectInputStream(fin);
 Object o = ois.readObject();