复习序列化与反序列化的概念,要求自定义Person类,其中三个属性name,age,school.
age属性不作为序列化保存而其他两个属性使用序列化保存在本地文件TestSer.txt中。
使用序列化和反序列化的方式将自定义类序列化与反序列化操作。
package bite.IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
@SuppressWarnings("serial")
class Person implements Serializable{
private String name;
private transient int age;
private String school;
public Person(String name, int age, String school) {
super();
this.name = name;
this.age = age;
this.school = school;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", school=" + school + "]";
}
}
public class XuLieHua_FanXuLieHua {
public static void main(String[] args) throws Exception {
Person person=new Person("宋典", 21, "西安科技大学");
File file=new File("C:"+File.separator+"Users"+File.separator+
"宋典"+File.separator+"Desktop"+File.separator+"TestSer.txt");
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
OutputStream out=new FileOutputStream(file);
InputStream in=new FileInputStream(file);
@SuppressWarnings("resource")
ObjectOutputStream oos=new ObjectOutputStream(out);
oos.writeObject(person);
out.close();
ObjectInputStream ois=new ObjectInputStream(in);
System.out.println(ois.readObject());
ois.close();
}
}
序列化输出后的文件内容:
反序列化后的输出结果