2018-11-25

2018-11-25  本文已影响0人  roky_e

android中的序列化

(注意):静态成员变量属于类不属于对象,所以不会参加序列化过程;其次用transient关键字标记的成员变量比参与序列化过程。

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();
}
上一篇 下一篇

猜你喜欢

热点阅读