流_对象流的使用

package com.zhou.java;

import org.junit.Test;

import java.io.*;

/**
 * 对象流的使用:
 * 1.ObjectInputStream 和 ObjectOutputStream
 * 2.作用:用于存储和读取基本数据类型或对象的处理流. 它的强大之处就是可以把 Java 中的对象写入到数据源中,也能把对象从数据源中还原出来
 *
 * 3. 要想一个 java 对象是可序列化的,需要满足相应的要求. 见 Person.java
 *
 * @author upzhou
 * @create 2022-03-30 20:10
 */
public class ObjectInputOutputStreamTest {
    /*
    序列化过程: 将内存中的 Java 对象保存到磁盘中或通过网络传输出去
    使用 ObjectOutputStream 实现
     */
    @Test
    public void testObjectOutputStream(){
        ObjectOutputStream oos = null;
        try {
            //1.
            oos = new ObjectOutputStream(new FileOutputStream("object.data"));
            //2.
            oos.writeObject(new String("我和我的祖国"));
            oos.flush();//刷新操作

            oos.writeObject(new Person("王明",23));
            oos.flush();

            oos.writeObject(new Person("李红",23,1001,new Account(5000)));
            oos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null){
                //3.
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*
    反序列化:将磁盘文件中的对象还原为内存中的一个 java 对象
    使用 ObjectInputStream 实现
     */
    @Test
    public void testObjectInputStream(){

        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.data"));

            Object obj = ois.readObject();
            String str = (String) obj;

            Person p = (Person) ois.readObject();
            Person p1 = (Person) ois.readObject();

            System.out.println(str);
            System.out.println(p);
            System.out.println(p1);

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

            }
        }
    }
}

 

posted @ 2022-04-30 14:59  UpZhou  阅读(13)  评论(0)    收藏  举报