如何序列化一个对象并将其保存到 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 中我是新手,所以我完全迷失了。

155235 次浏览

保存(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();

我已经尝试了这两个选项(读/写) ,使用普通对象、对象数组(150个对象)、映射:

选择一:

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

选择二:

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);

完成代码与错误处理和添加的文件流关闭。将它添加到您希望能够序列化和反序列化的类中。在我的例子中,类名是 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);

我刚创建了一个类用 Generics 处理这个问题,这样它就可以用于所有可序列化的对象类型:

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);
}


}

我使用 SharePrefrances:

package myapps.serializedemo;


import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;


import java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


//Create the SharedPreferences
SharedPreferences sharedPreferences = this.getSharedPreferences("myapps.serilizerdemo", Context.MODE_PRIVATE);
ArrayList<String> friends = new ArrayList<>();
friends.add("Jack");
friends.add("Joe");
try {


//Write / Serialize
sharedPreferences.edit().putString("friends",
ObjectSerializer.serialize(friends)).apply();
} catch (IOException e) {
e.printStackTrace();
}
//READ BACK
ArrayList<String> newFriends = new ArrayList<>();
try {
newFriends = (ArrayList<String>) ObjectSerializer.deserialize(
sharedPreferences.getString("friends", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
}
Log.i("***NewFriends", newFriends.toString());
}
}

必须将 ObjectSerialization 类添加到程序中,以下操作可能有效

    import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class ObjectSerializer {


public static String serialize(Serializable obj) throws IOException {
if (obj == null) return "";
try {
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}


public static Object deserialize(String str) throws IOException {
if (str == null || str.length() == 0) return null;
try {
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}


public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();


for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}


return strBuf.toString();
}


public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i+=2) {
char c = str.charAt(i);
bytes[i/2] = (byte) ((c - 'a') << 4);
c = str.charAt(i+1);
bytes[i/2] += (c - 'a');
}
return bytes;
}

}

如果使用 SharedPreferences 存储数组,则使用以下方法:-

SharedPreferences sharedPreferences = this.getSharedPreferences(getPackageName(),MODE_PRIVATE);

序列化:-

sharedPreferences.putString("name",ObjectSerializer.serialize(array));

反序列化:-

newarray = (CAST_IT_TO_PROPER_TYPE) ObjectSerializer.deSerialize(sharedPreferences.getString(name),null);