接下来对序列化进行一些介绍
一、定义
序列化是将对象的状态信息转换为存储或传输的形式的过程。在序列化期间,对象将其当前状态写入到临时或持久性存储区。以后,可以通过从储存区中读取或反序列化对象的状态,重新创建该对象。
简而言之
- 序列化是将对象转换成字节流
- 反序列化是将字节流转化成对象。
二、用途
主要用途:
- 序列化将对象写成字节流持久化保存在内存、文件、数据库中
- 将序列化对象通过网络传输到其他客户端
在Android开发中,Intent、Bundle和Binder数据传输时,其对象都需要序列化。例:
public Intent putExtra(String name, Parcelable value) {
...}
public Intent putExtra(String name, Serializable value) {
...}
三、序列化接口介绍
在Android序列化的方式有两种
- Serializable 接口
- Parcelable 接口
接下来对这两个序列化接口分别介绍:
1、Serializable 接口
Serializable 接口是java提供一个序列化空接口,序列化过程也很简单,只需实现Serializable接口即可:
//空接口
public interface Serializable {
}
public class User implements Serializable{
private String userName;
private String userId;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
一个对象的序列化和反序列化实现:
- 使用ObjectOutputStream进行对象序列化
- 使用ObjectInputStream字节流反序列化成对象
例子:
/**
* 序列化
*/
public synchronized static boolean saveUser(User user,String path){
try {
File file = new File(path);
//判断文件是否存在
if (file.exists()){
//删除
file.delete();
}
//创建文件
file