美文网首页
Java 序列化与反序列化,及注意事项

Java 序列化与反序列化,及注意事项

作者: LX_代码制造坊 | 来源:发表于2020-05-06 21:59 被阅读0次
    import java.io.*;
    
    public class ObjectFile {
        public static void main(String[] args) throws IOException {
            //xuliehua();
            fanxuliehua();
        }
    
        /**
         * 反序列化
         */
        private static void fanxuliehua() throws IOException {
            ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("bb/b/o.txt"));
            try {
               Object o = objectInputStream.readObject();
    
               objectInputStream.close();
                System.out.println(o.toString());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 序列化
         */
        public static void xuliehua() throws IOException {
            Dog dog = new Dog("mimi",12);
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream("bb/b/o.txt"));
            objectOutputStream.writeObject(dog);//将对象写入序列化文件中存储起来
            objectOutputStream.close();
        }
    }
    
    //需要序列化的类,必须实现Serializable接口
    class Dog implements Serializable {
        private static final long serialVersionUID =1L;  //防止序列化后,由于类的改变引起InvialidClassException;
        private String name;
        private int age;
    
        public Dog(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "Dog{" +
                    "name='" + name + '\'' +
                    ", 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;
        }
    }
    

    相关文章

      网友评论

          本文标题:Java 序列化与反序列化,及注意事项

          本文链接:https://www.haomeiwen.com/subject/gkngghtx.html