2010-11-07 45 views
101

说我有一些简单的类,一旦它被实例化为一个对象,我希望能够将其内容序列化到一个文件,并通过稍后加载该文件来检索它...我不知道从哪里开始在这里,我需要做什么来将这个对象序列化到一个文件?如何序列化对象并将其保存到Android中的文件中?

public class SimpleClass { 
    public string name; 
    public int id; 
    public void save() { 
     /* wtf do I do here? */ 
    } 
    public static SimpleClass load(String file) { 
     /* what about here? */ 
    } 
} 

这可能是世界上最简单的问题,因为这是在.NET中一个非常简单的任务,但在Android的我很新,所以我完全丧失。

回答

217

保存(W/O异常处理代码):

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); 
ObjectOutputStream os = new ObjectOutputStream(fos); 
os.writeObject(this); 
os.close(); 
fos.close(); 

加载(W/O异常处理代码):

FileInputStream fis = context.openFileInput(fileName); 
ObjectInputStream is = new ObjectInputStream(fis); 
SimpleClass simpleClass = (SimpleClass) is.readObject(); 
is.close(); 
fis.close(); 
+0

非常有用。你能否解释一下,我们是否需要序列化类作为目标文件进行写入。 – 2012-05-10 09:25:54

+4

如果您使用Serializable接口,则将此功能隐式添加到您的类中。如果你想要的只是简单的对象序列化,那就是我会用到的。这也非常容易实施。 http://developer.android.com/reference/java/io/Serializable.html – mtmurdock 2012-08-09 22:07:11

+5

+1,对于多个对象保存有一个技巧要求:http://stackoverflow.com/a/1195078/1321401 – Luten 2013-10-03 16:39:15

30

我已经试过这2个选项(读/写)与普通的对象,对象的阵列(150个对象),地图:

选项1:

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); 
ObjectOutputStream os = new ObjectOutputStream(fos); 
os.writeObject(this); 
os.close(); 

选项2:

SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE); 
SharedPreferences.Editor ed=mPrefs.edit(); 
Gson gson = new Gson(); 
ed.putString("myObjectKey", gson.toJson(objectToSave)); 
ed.commit(); 

选项2比选项1

两次较快的选项2不便之处在于你必须做出具体的代码读取:

Gson gson = new Gson(); 
JsonParser parser=new JsonParser(); 
//object arr example 
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray(); 
events=new Event[arr.size()]; 
int i=0; 
for (JsonElement jsonElement : arr) 
    events[i++]=gson.fromJson(jsonElement, Event.class); 
//Object example 
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class); 
4

带有错误处理和添加文件流的完整代码关闭。将它添加到你想要能够序列化和反序列化的类中。在我的案例中,班级名称是CreateResumeForm。您应该将其更改为您自己的班级名称。 Android接口Serializable不足以将对象保存到文件,它只创建流。

// Constant with a file name 
public static String fileName = "createResumeForm.ser"; 

// Serializes an object and saves it to a file 
public void saveToFile(Context context) { 
    try { 
     FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); 
     ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); 
     objectOutputStream.writeObject(this); 
     objectOutputStream.close(); 
     fileOutputStream.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 


// Creates an object by reading it from a file 
public static CreateResumeForm readFromFile(Context context) { 
    CreateResumeForm createResumeForm = null; 
    try { 
     FileInputStream fileInputStream = context.openFileInput(fileName); 
     ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); 
     createResumeForm = (CreateResumeForm) objectInputStream.readObject(); 
     objectInputStream.close(); 
     fileInputStream.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 
    return createResumeForm; 
} 

使用它像这样在你的Activity

form = CreateResumeForm.readFromFile(this); 
6

我只是做了一类具有泛型来处理这个问题,所以它可以是序列化的所有对象类型中:

public class SerializableManager { 

    /** 
    * Saves a serializable object. 
    * 
    * @param context The application context. 
    * @param objectToSave The object to save. 
    * @param fileName The name of the file. 
    * @param <T> The type of the object. 
    */ 

    public static <T extends Serializable> void saveSerializable(Context context, T objectToSave, String fileName) { 
     try { 
      FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); 
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); 

      objectOutputStream.writeObject(objectToSave); 

      objectOutputStream.close(); 
      fileOutputStream.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * Loads a serializable object. 
    * 
    * @param context The application context. 
    * @param fileName The filename. 
    * @param <T> The object type. 
    * 
    * @return the serializable object. 
    */ 

    public static<T extends Serializable> T readSerializable(Context context, String fileName) { 
     T objectToReturn = null; 

     try { 
      FileInputStream fileInputStream = context.openFileInput(fileName); 
      ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); 
      objectToReturn = (T) objectInputStream.readObject(); 

      objectInputStream.close(); 
      fileInputStream.close(); 
     } catch (IOException | ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 

     return objectToReturn; 
    } 

    /** 
    * Removes a specified file. 
    * 
    * @param context The application context. 
    * @param filename The name of the file. 
    */ 

    public static void removeSerializable(Context context, String filename) { 
     context.deleteFile(filename); 
    } 

} 
相关问题