1.为什么要序列化
在开发中,经常需要将对象的信息保存到磁盘中以便于以后检索。如果逐一的对对象的属性进行操作通常是非常繁琐的,而且容易出错。简单的说,序列化就是将对象的状态存储到特定的存储介质中的过程,也就是将对象状态转换为可保持或可传输的过程。其实,就是把对象转换为流,写入到文件中。反序列化就是把写入文件的内容读取出来。
2.实例
package IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable {
String name;
String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
public class Serial_ext {
public static void main(String[] args) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("E:\\stu.txt"));
Student stu = new Student();
stu.setName("李白");
stu.setAge("20");
oos.writeObject(stu);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
package IO;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Serial_get {
public static void main(String[] args) throws ClassNotFoundException {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("E:\\stu.txt"));
Student stu = (Student) ois.readObject();
System.out.println("学生姓名:" + stu.getName());
System.out.println("学生年龄:" + stu.getAge());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}