序列化
一、序列化:serialization
- 解释:玩闯关游戏时,需要把当前游戏记录存储到文件中,以便下次游戏时能从当前位置继续。
- 特点:序列化的文件很难让一般人阅读,但它比纯文本文件更容易让程序恢复原先状态,也比较安全。
如果要让类能够被序列化,就实现serializable接口
/**
* 序列化的学习
*/
public class Serialization {
public static void main(String[] args) {
Person p1 =new Person();
p1.setName("hhh");
p1.setOld(18);
Person p2 =new Person();
p2.setName("hhh");
p2.setOld(18);
try {
FileOutputStream fileOutputStream = new FileOutputStream("myGame.ser");
ObjectOutputStream oStream = new ObjectOutputStream(fileOutputStream);
oStream.writeObject(p1);
} catch (Exception e) {
e.printStackTrace();
}
}
static class Person implements Serializable{
String name;
int old;
public Person(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getOld() {
return old;
}
public void setOld(int old) {
this.old = old;
}
}
}
//myGame.ser不存在时将被创建出来
序列化是全有或全无的,不会出现只保存一半的情况
如果存在类A和类B,类A实现serializable,并在类A中new B();如果类B没有实现serializable,那么无法对A 的对象实现序列化
如果在序列化中需要跳过某个变量,可以在变量前加标记 transient(瞬时)