首页新闻找找看学习计划

java 序列化与反序列化多个对象 抛出异常

0
悬赏园豆:5 [已解决问题] 解决于 2019-09-12 19:43

jdk 1.8 IEDA
设置可以追加写入后,向目标文件序列化多个同一对象,再序列化出来时,因为反序列化时头部信息只读取一次,报出异常。
请问该怎么解决?或者代码写的有问题?

import java.io.*;

/**
 * 完成多个对象的序列化和反序列化
 */
public class SerializationDeserialization {
    public static void main(String[] args) {
        Staff staff1 = new Staff("银灰", "近卫", 880, 400);
        Staff staff2 = new Staff("伊芙利特", "术师", 748, 120);
        Staff staff3 = new Staff("能天使", "狙击", 571, 140);
        seralization(staff1);
        seralization(staff2);
        seralization(staff3);

        File file = new File("arknights.txt");
        try {
            deseralization(file);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 序列化
     * @param staff
     */
    public static void seralization(Staff staff) {
        //设置可以追加写入
        try (ObjectOutputStream oosOut = new ObjectOutputStream(new FileOutputStream("arknights.txt", true))) {
            oosOut.writeObject(staff);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反序列化
     * @param file
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void deseralization(File file) throws IOException, ClassNotFoundException {
        ObjectInputStream oosIn = new ObjectInputStream(new FileInputStream(file));
        Object obj;
        while ((obj=oosIn.readObject())!=null) {
            Staff staff=(Staff)obj;     // Staff{name='银灰',position='近卫',atk='880',def='400'}
                                        // java.io.StreamCorruptedException: invalid type code: AC
            System.out.println(staff);
        }
    }
}
< >
分享
最佳答案
0
收获园豆:5
不安分的黑娃 | 菜鸟二级 |园豆:215 | 2019-09-12 14:31
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册