刚好接触到要用的思路,扩充下

1 对象序列化

1.1 对象要序列化要实现Serializable接口

1.2 然后通过ObjectInputStream 对象读入流来读入一个对象

new ObjectOutputStream(new xxOutputStream(""))
new的时候传入一个读入流

1.3 需要申明一个序列化版本号

private static final long serialVersionUID = ;
//用于协商该类的版本,序列化和反序列的版本号不一致时,会异常。修订后应该修改版本号,这样之前序列化的对象进行反序列的时候会失败,抛异常。
//序列化对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(""));
//写入
oos.writeObject();


ObjectInputStream ois = new ObjectInputStream(new FileInputStream(""));
//读进
Object o = ois.readObject();

1.4 序列化对象——文件

public class Main {
    public static void main(String[] args) throws ClassNotFoundException {
        Vector<Integer> list1 = new Vector<>();

        list1.add(2);


        try {
            FileOutputStream fileOutputStream = new FileOutputStream("data.txt");

            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(list1);

            objectOutputStream.flush();

            FileInputStream fileInputStream = new FileInputStream("data.txt");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            Object o = objectInputStream.readObject();
            List<Integer> list2 = (List<Integer>) o;

            System.out.println(list2.get(0));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

1.5序列化对象——字节

public class Main {
    public static void main(String[] args) throws ClassNotFoundException {
        Vector<Integer> list1 = new Vector<>();

        list1.add(2);

        try {

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(list1);

            objectOutputStream.flush();

//            String s = objectOutputStream.toString();

            byte[] bytes = byteArrayOutputStream.toByteArray();

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Object o = objectInputStream.readObject();
            List<Integer> list2 = (List<Integer>) o;

            System.out.println(list2.get(0));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
 posted on 2023-04-19 00:04    阅读(47)  评论(0编辑  收藏  举报