2011年计算机二级考试JAVA知识点整理(42)

2014-11-01 12:15:08 · 作者: · 浏览: 58

  1.3.8 对象流


  串行化:对象通过写出描述自己状态的数值来记述自己的过程叫串行话


  对象流:能够输入输出对象的流


  将串行化的对象通过对象流写入文件或传送到其他地方


  对象流是在普通流上加了传输对象的功能,所以构造对象流时要先构造普通文件流


  注意:只有实现了Serializable接口的类才能被串行化


  例子:


  import java.io.*;


  class Student implements Serializable{


  private String name;


  private int age;


  public Student(String name,int age){


  this.name=name;


  this.age=age;


  }


  public void greeting(){


  System.out.println("hello ,my name is "+name);


  }


  public String toString(){


  return "Student["+name+","+age+"]";


  }


  }


  public class ObjectOutTest{


  public static void main(String args[]){


  ObjectOutputStream oos=null;


  try{


  oos=new ObjectOutputStream(


  new FileOutputStream("student.txt"));


  Student s1=new Student("Jerry",24);


  Student s2=new Student("Andy",33);


  oos.writeObject(s1);


  oos.writeObject(s2);


  }catch(Exception e){


  e.printStackTrace();


  }finally{


  if(oos!=null)


  try{


  oos.close();


  }catch(Exception e){


  e.printStackTrace();


  }


  }


  }


  }


  import java.io.*;


  public class ObjectInTest{


  public static void main(String args[]){


  ObjectInputStream ois=null;


  Student s=null;


  try{


  ois=new ObjectInputStream(


  new FileInputStream("student.txt"));


  System.out.println("--------------------");


  s=(Student)ois.readObject();


  System.out.println(s);


  s.greeting();


  System.out.println("--------------------");


  s=(Student)ois.readObject();


  System.out.println(s);


  s.greeting();


  }catch(Exception e){


  e.printStackTrace();


  }finally{


  if(ois!=null)


  try{


  ois.close();


  }catch(Exception e){


  e.printStackTrace();


  }


  }


  }


  }


  编辑推荐: