黑马程序员技术交流社区
标题:
对象序列化和反序列化案例
[打印本页]
作者:
hero_king
时间:
2016-6-1 22:13
标题:
对象序列化和反序列化案例
新建一个Student类实现Serializable接口:
import java.io.Serializable;
/*
* 序列化和反序列化使用的学生类
*/
public class Student implements Serializable{
/**
*
*/
private static final long serialVersionUID = -2279895898508761128L;
private String name;
private transient int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + <div class="blockcode"><blockquote>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
* 对象序列化和反序列化流的使用
*/
public class Demo7 {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
Student s = new Student("张三", 25);
File file = new File("序列化.txt");
write(file, s);
read(file);
}
// 序列化对象
private static void write(File file, Student s) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
file));
oos.writeObject(s);
}
// 反序列化对象
private static void read(File file) throws IOException,
ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Object o = ois.readObject();
System.out.println(o);
}
}
复制代码
name + ", age=" + age + "]";
}
}测试案例:
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2