首页 > 代码库 > 序列化(ObjectOutputStream和ObjectInputStream)(切记:out是输出到本地中,in是输入到程序中)

序列化(ObjectOutputStream和ObjectInputStream)(切记:out是输出到本地中,in是输入到程序中)

注意:序列化自定义类必须实现一个接口Serializable,在c#中序列化自定义类是使用特性也就是[Serializable]

//要实现序列化的类

public class Student implements Serializable {
 /**
  *
  */
 private static final long serialVersionUID = 1L;//序列版本号
 private String name;
 private int age;
 public Student(String name,int age){
  this.name = name;
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

 

//ObjectOutputStream

public class ObjectOutputStreamDemo {
 /**
  * 序列化步骤:
  * 1、创建字节流
  * 2、创建序列化流
  * 3、序列化操作
  * 4、关闭流
  */
 //使用序列化前提:保证进行序列化的类要实现Serializable接口
 public static void main(String[] args) {

Student stu = new Student("张三",23);
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
  try {
   //1、创建字节流
   fos =new FileOutputStream("student.stu");
   //2、创建序列化流
   oos = new ObjectOutputStream(fos);
   //序列化操作
   oos.writeObject(stu);
   System.out.println("序列化成功!");
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   try {
    //4、关闭流
    oos.close();
    fos.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }  
  }
 }

}

 

//ObjectInputStream

public class ObjectInputStreamDemo {
 //反序列化
 public static void main(String[] args) {

FileInputStream fis = null;
  ObjectInputStream ois = null;
  try {
   fis = new FileInputStream("student.stu");
   ois = new ObjectInputStream(fis);
   Student student = (Student)ois.readObject();
   System.out.println(student.getName()+"-"+student.getAge());
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally{
   try {
    ois.close();
    fis.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
  
 }

}