序列化和反序列化的用法

来源:互联网 发布:百度推广优化三尾狐 编辑:程序博客网 时间:2024/06/13 07:41

//首先构建一个类并声明类的属性

import java.io.Serializable;



public class Person implements Serializable{


public String name;
public int age;

public Person(String name,int age){
this.name = name;
this.age = age;
}

}

//序列化对象

public class GameEnd {


public static void main(String[] args) throws FileNotFoundException, IOException {
//序列化对象

Person[] p = {new Person("小明",20),new Person("小赵",20)};
List list = new ArrayList();
list.addAll(Arrays.asList(p));

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:\\tempGames.zd"));

oos.writeObject(list);
oos.close();


}


}

//反序列化对象

public class GameStart {


public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
//反序列化

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\tempGames.zd"));
// Person[] p = (Person[]) ois.readObject();
//
// for (Person person : p) {
//
// System.out.println(person.name+" "+person.age);
// }

List list = (List) ois.readObject();

for (Object obj : list) {
if(obj instanceof Person){
Person p = (Person) obj;
System.out.println(p.name+" "+p.age);
}
}

ois.close();


}


}

0 0
原创粉丝点击