天天看点

Java复习——对象流、序列化

package com.atguigu.objectInputStream;

import com.atguigu.JavaImportant.Person;

import org.junit.Test;

import java.io.*;

public class ObjectInputOutputStreamTest {

@Test

public void test1(){

ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(new FileOutputStream("object.dat"));

        oos.writeObject(new String("天天上班上天天"));

        oos.flush();//刷新操作
        /**
         * person类需要满足2个条件:
         * 1、实现接口:serializable
         * 2、当前类提供一个全局常量:serialVersionUID --->  版本兼容,不加的话 JAVA会自动分配一个serialVersionUID
         * (但是当当前类有改动时,反序列化时分配serialVersionUID则于序列化时的serialVersionUID则不一致,导致程序报错)
         * 3、类的属性也必须要可序列化(默认情况下,基本数据类型都是可序列化的)
         *
         *
         * 补充:ObjectInputStream和ObjectOutputStream不可序列化static和transient修饰的成员变量
         *
         */
        oos.writeObject(new Person(18,"小明"));
        oos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (oos != null){
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

@Test
//反序列化过程:将磁盘文件中的对象还原为内存中的一个java对象
//使用 ObjectInputStream实现
public  void  test2(){
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("object.dat"));

        Object object = ois.readObject();
        String str = (String) object;
        System.out.println(str);
        person = (Person) ois.readObject();
        Person person = new Person();
        System.out.println(person);


    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {

        if (ois != null){
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    }
           

}