android中的序列化
(注意):静态成员变量属于类不属于对象,所以不会参加序列化过程;其次用transient关键字标记的成员变量比参与序列化过程。
实现序列化化有两种方式:
1.Serializable: java和android中都可以使用
2.Parcelable: android中特有的-
实现方式,首先来看Serializable:
1.使类实现Serializable接口
2.在类的声明中指定一个类似下面的标识(非必须,但是在反序列化的时候会有影响)private static final long serialVersionUID =1L
- 实例:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
public int userId;
public String userName;
public boolean isMale;
public User(int userId, String userName, boolean isMale) {
this.userId = userId;
this.userName = userName;
this.isMale = isMale;
}
}
//序列化过程
User user = new User(0, "jack", true);
try {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("cache.txt"));
out.writeObject(user);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
//反序列化过程
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("cache.txt"));
User newUser = (User) in.readObject();
} catch (IOException e) {
e.printStackTrace(
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
- Parcelable