码迷,mamicode.com
首页 > 编程语言 > 详细

Java 序列化与反序列化

时间:2020-02-19 05:37:05      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:tst   序列化   puts   void   get   反序   sim   getname   res   


import org.junit.Test;
import java.io.*;

public class SerializableTest implements Serializable {


    class Student implements Serializable {
        private String name;
        private String gender;
        private String address;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getGender() {
            return gender;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", gender='" + gender + '\'' +
                    ", address='" + address + '\'' +
                    '}';
        }
    }

    /**
     * 序列化
     */
    @Test
    public void serializable() {
        Student student = new Student();
        student.setName("Simon");
        student.setGender("male");
        student.setAddress("WuHan");

        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("k:/object.dat"));
            outputStream.writeObject(student);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反序列化
     */
    @Test
    public void deserialization() {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("k:/object.dat"));
            Object o = objectInputStream.readObject();
            System.out.println(o.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}

Java 序列化与反序列化

标签:tst   序列化   puts   void   get   反序   sim   getname   res   

原文地址:https://www.cnblogs.com/Haidnor/p/12329643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!