package com.sf.day22;

import com.sun.corba.se.impl.interceptors.PICurrent;
import org.junit.Test;
import org.omg.CORBA.PUBLIC_MEMBER;
import sun.misc.OSEnvironment;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Test02 {

    @Test
    public void save() throws IOException {
        String name = "张三";
        int age = 18;
        double height = 182;
        boolean flag = false;

        //序列化
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("save.dat"));
        oos.writeUTF(name);
        oos.writeInt(age);
        oos.writeDouble(height);
        oos.writeBoolean(flag);
        oos.close();
    }

    /**
     * 反序列化
     */
    @Test
    public void t2() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("save.dat"));
        String name = ois.readUTF();
        System.out.println(name);
        System.out.println(ois.readInt());
        System.out.println(ois.readDouble());
        System.out.println(ois.readBoolean());
        ois.close();
    }

    @Test
    public void t3() throws IOException{
        Employee employee = new Employee((byte) 12,"zhangsan",12,190.8,true);
        //创建序列化的对象流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee1.dat"));
        oos.writeObject(employee);
        //关闭资源
        oos.close();
    }

    /**
     * 对Employee对象进行反序列化
     * @throws IOException
     */
    @Test
    public void t4() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee1.dat"));
        Object o = ois.readObject();
        if(o instanceof Employee){
            Employee employee = (Employee) o;
            System.out.println(employee);
        }
        //关闭资源
        ois.close();
    }

    @Test
    public void t5() throws IOException{
        User user1 = new User("admin1",1001);
        User user2 = new User("admin2",1002);
        User user3 = new User("admin3",1003);
        User user4 = new User("admin4",1004);
        User user5 = new User("admin5",1005);

        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.dat"));
        oos.writeObject(userList);
        oos.close();
    }

    @Test
    public void t6() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.dat"));
        Object o = ois.readObject();
        //转换成集合
        System.out.println(o);
        List<User> userList = (List<User>) o;
        for (User user : userList) {
            System.out.println(user);
        }
    }
}
