序列化是将对象转换为可保持或传输格式的过程,反序列化是将流转化成对象。
代码如下
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Person(){
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeToFile {
private ObjectInputStream ois;
public static void main(String args[]) {
SerializeToFile stf = new SerializeToFile();
stf.savePerson();
stf.restorePerson();
}
public void savePerson() {
Person myPerson = new Person("Jack",19);
try {
FileOutputStream fileout = new FileOutputStream("E:\\myPerson.txt");
ObjectOutputStream oos = new ObjectOutputStream(fileout);
oos.writeObject(myPerson);
oos.flush();
oos.close();
} catch(Exception e) {
e.printStackTrace();
}
}
public void restorePerson() {
try {
FileInputStream fis = new FileInputStream("E:\\myPerson.txt");
ois = new ObjectInputStream(fis);
Person myPerson = (Person)ois.readObject();
System.out.println("Name is: "+myPerson.getName());
System.out.println("Age is: "+myPerson.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}
其中savePerson()方法将myPerson对象序列化到文本myPerson.txt中,而restorePerson()方法将流文本反序列化成对象myPerson
运行结果为:
Name is: Jack
Age is: 19