0

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

这是代码:

 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" />

我怎么能把它存储在手机内存中@有人能帮我吗@谢谢

4

1 回答 1

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();
于 2013-05-22T09:06:47.283 回答