阅读量:124
在 Android 中,可以使用 Serializable 接口或 Parcelable 接口来序列化数据。下面分别介绍这两种方法的使用:
- 使用 Serializable 接口序列化数据:
- 首先,需要在要序列化的数据类中实现 Serializable 接口,例如:
public class MyData implements Serializable {
private String name;
private int age;
// 构造方法、getter 和 setter 方法等
}
- 然后,在需要序列化数据的地方,可以使用 ObjectOutputStream 来将数据序列化成字节流,例如:
MyData data = new MyData("John", 25);
try {
FileOutputStream fileOut = new FileOutputStream("data.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(data);
out.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
- 最后,可以使用 ObjectInputStream 来反序列化数据,例如:
MyData data = null;
try {
FileInputStream fileIn = new FileInputStream("data.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
data = (MyData) in.readObject();
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
- 使用 Parcelable 接口序列化数据:
- Parcelable 接口比 Serializable 接口更高效,在性能上更好,但需要实现更多的方法。首先,在要序列化的数据类中实现 Parcelable 接口,例如:
public class MyData implements Parcelable {
private String name;
private int age;
// 构造方法、getter 和 setter 方法等
// 实现 Parcelable 接口的方法
}
- 然后,使用 Parcel 类来序列化和反序列化数据,例如:
MyData data = new MyData("John", 25);
// 序列化数据
Parcel parcel = Parcel.obtain();
data.writeToParcel(parcel, 0);
// 反序列化数据
parcel.setDataPosition(0);
MyData newData = MyData.CREATOR.createFromParcel(parcel);
parcel.recycle();
以上就是在 Android 中序列化数据的两种方法,开发者可以根据自己的需求选择合适的方法来序列化数据。