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

本文将介绍如何在C#中实现序列化自定义类,并通过具体代码实例演示序列化步骤,包括创建字节流、序列化流、序列化操作及关闭流的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意:序列化自定义类必须实现一个接口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();
   }
  }
  
  
 }

}

转载于:https://www.cnblogs.com/danmao/p/3825254.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值