java序列化和反序列化
来源:互联网 发布:minix3.3.0源码 编辑:程序博客网 时间:2024/05/16 12:46
1.首先要建一个类,该类要实现Serializable接口
import java.io.Serializable;
public class Student implements Serializable{
String name;
int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
2.测试使用
//序列化
//实例化对象
Student s1 = new Student(“tom”,22);
//把对象保存到本地,用字节输出流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(“D:\ad\mmm.aaa”));
oos.writeObject(s1);
oos.close();
//反序列化
FileInputStream fi=new FileInputStream(“D:\ad\mmm.aaa”);
ObjectInputStream ob=new ObjectInputStream(fi);
Object obj=ob.readObject(); fi.close(); ob.close(); Student stu=(Student)obj; System.out.println(stu.name); System.out.println(stu.age);
//如果报异常,检查一下你是否实现了Serializable接口
阅读全文