• Java对象的序列化和反序列化


     1 package FileDemo;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.ObjectInputStream;
     7 import java.io.ObjectOutputStream;
     8 import java.io.Serializable;
     9 
    10 class Person implements Serializable {
    11     /*
    12      * 接口标记,需要被序列化的对象必须实现Serializable接口 否则会出现NotSerializableException异常
    13      */
    14     String name;
    15     int age;
    16 
    17     public Person(String name, int age) {
    18         super();
    19         this.name = name;
    20         this.age = age;
    21     }
    22 
    23     public String getName() {
    24         return name;
    25     }
    26 
    27     public void setName(String name) {
    28         this.name = name;
    29     }
    30 
    31     public int getAge() {
    32         return age;
    33     }
    34 
    35     public void setAge(int age) {
    36         this.age = age;
    37     }
    38 
    39 }
    40 
    41 public class ObjectStreamDemo {
    42 
    43     /**
    44      * @param args
    45      * @throws Exception
    46      */
    47     public static void main(String[] args) throws Exception {
    48 
    49         writeObject();
    50         readObject();
    51     }
    52 
    53     private static void readObject() throws Exception {
    54         ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
    55                 "object.object"));
    56         Person  obj = (Person)ois.readObject();
    57         System.out.println(obj.getName()+":"+obj.getAge());
    58     }
    59 
    60     private static void writeObject() throws IOException, IOException {// 对象的序列化
    61         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
    62                 "object.object"));
    63         oos.writeObject(new Person("Java", 20));
    64         oos.writeObject(new Person("python", 40));
    65         oos.writeObject(new Person("linux", 50));
    66         oos.writeObject(new Person("ruby", 46));
    67         oos.close();
    68     }
    69 
    70 }
  • 相关阅读:
    js复习---工厂函数---构造函数的执行过程
    21年初的措不及防-------
    element ui checkbox实现多项全选反选功能
    vue 实现导航锚点联动
    this.$router.currentRoute 和 this.$route的 区别
    重置vue组件的data数据 this.$options.data()
    父组件中如何拿到引入的子组件里element-ui 的form表单ref对象
    线程笔记
    面向对象
    关于上传和下载的笔记
  • 原文地址:https://www.cnblogs.com/ysw-go/p/5308794.html
Copyright © 2020-2023  润新知