序列化学习
//前提是Student类已经实现Serializable接口
//这是前提,然后再进行序列化和反序列
package IO;
import java.io.*;
public class Usestudent {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu=new Student("TOM",'M',20,3.6);
File f=new File("D:"+File.separator+"hello3.txt");
//序列化到文件里面,所以必须先创建一个file
try
{
f.createNewFile();
}
catch(IOException e)
{
e.printStackTrace();
}
//序列化
try {
FileOutputStream out=new FileOutputStream(f);//1、文件流
ObjectOutputStream ob1=new ObjectOutputStream(out);//序列流
ob1.writeObject(stu);//目标对象写入
out.close();
ob1.close();
//反序列化
FileInputStream in=new FileInputStream(f);
ObjectInputStream ob2=new ObjectInputStream(in);
Student st1=(Student)ob2.readObject();//将字节序列返回成student对象
System.out.println("name = " + st1.getName());
System.out.println("sex = " + st1.getSex());
System.out.println("year = " + st1.getYear());
System.out.println("gpa = " + st1.getGpa());
in.close();
ob2.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}