序列化

来源:互联网 发布:不要网络的搜题软件 编辑:程序博客网 时间:2024/05/16 18:28
序列化学习
//前提是Student类已经实现Serializable接口//这是前提,然后再进行序列化和反序列package IO;import java.io.*;public class Usestudent {public static void main(String[] args) {// TODO Auto-generated method stubStudent stu=new Student("TOM",'M',20,3.6);File f=new File("D:"+File.separator+"hello3.txt");//序列化到文件里面,所以必须先创建一个filetry{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 blocke.printStackTrace();}catch (IOException e)  {   e.printStackTrace();  } catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

原创粉丝点击