0004-java对象的序列化和反序列化

package com.zxjbigboy.serialize;

import lombok.Data;

import java.io.Serializable;

/**
 * Created by zhaoxiaojun on 16/7/6.
 *
 * 被测试的java对象
 */
@Data
public class Student implements Serializable {
    //序列化常量ID
    public static final Long serialVersionUID = 1L;
    
    private String name;
    
    private Integer age;
    



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

}

package com.zxjbigboy.serialize;

import java.io.*;

/**
 * Created by zhaoxiaojun on 16/7/6.
 * 本例程给出对象的序列化和反序列化的方法
 */
public class SerializeTest {

    /**
     * 将一个java对象转换为字节数组,从字节数组中读取一个java对象
     */
    public static void byteStreamTest(){
        Student a = new Student();
        a.setAge(8);
        a.setName("张三");
        try{
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileOutputStream fos = new FileOutputStream("serialTest.txt");
            ObjectOutputStream out = new ObjectOutputStream(baos);
            out.writeObject(a);
            out.close();
            System.out.println(baos.toByteArray());

            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
            Object o = in.readObject();
            in.close();
            if(o instanceof Student){
                Student a1 = (Student)o;
                a1.setName("李四");
                a1.setAge(9);
                System.out.println(a);
                System.out.println(a1);
            }
        }catch(IOException e){
            System.out.println(e);
        }catch (ClassNotFoundException ce){
            System.out.println(ce);
        }
    }

    /**
     * 将一个java对象转换为文件流存储,从文件流中读取并生成一个java对象
     */
    public static void fileStreamTest(){
        Student a = new Student();
        a.setAge(8);
        a.setName("张三");
        try {
            FileOutputStream fos = new FileOutputStream("serialTest.txt");
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(a);
            out.close();

            FileInputStream fis = new FileInputStream("serialTest.txt");
            ObjectInputStream in = new ObjectInputStream(fis);
            Object o = in.readObject();
            in.close();
            if(o instanceof Student){
                Student a1 = (Student)o;
                a1.setName("李四");
                a1.setAge(9);
                System.out.println(a);
                System.out.println(a1);
            }

        }catch (IOException ioe){
            System.out.println(ioe);
        }catch (ClassNotFoundException ce){
            System.out.println(ce);
        }
    }

    public static void main(String[] args) {
        byteStreamTest();
        fileStreamTest();
    }
}

你可能感兴趣的:(java)