You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java从文件读取对象不完整:仅能读取首个对象

序列化读取仅获取第一个对象的修复方案

问题根源

你的保存逻辑是循环写入所有Doctor对象,再循环写入所有Consultation对象,但读取逻辑只执行了两次readObject()——仅读取第一个Doctor和第一个Consultation就关闭了流,完全没处理后续的对象,自然只能拿到第一个。

修复后的读取方法

需要循环读取文件中的所有对象,直到触发EOFException(文件末尾),同时通过类型判断把对象加到对应的集合里:

void readData() throws IOException {
    try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("systemData.txt"))) {
        while (true) {
            try {
                Object obj = in.readObject();
                if (obj instanceof Doctor) {
                    doctorList.add((Doctor) obj);
                } else if (obj instanceof Consultation) {
                    consultations.add((Consultation) obj);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    } catch (EOFException ignored) {
        // 到文件末尾了,正常结束
    } catch (IOException e) {
        e.printStackTrace();
    }
}

更简洁的优化方案

如果想省掉逐个判断类型的麻烦,也可以直接把整个集合作为整体序列化,读写逻辑会简单很多:

优化后的保存方法

@Override
public void saveFile() {
    try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("systemData.txt"))) {
        out.writeObject(doctorList);
        out.writeObject(consultations);
        System.out.println("所有数据已保存");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

优化后的读取方法

void readData() throws IOException {
    try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("systemData.txt"))) {
        doctorList = (ArrayList<Doctor>) in.readObject();
        consultations = (ArrayList<Consultation>) in.readObject();
    } catch (EOFException ignored) {
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    } catch (ClassCastException ignored) {
    }
}

注意:不管用哪种方式,Doctor和Consultation类都必须实现Serializable接口,且类结构在序列化前后要保持一致(比如不要随意修改serialVersionUID,除非你明确知道怎么兼容旧数据)。

内容的提问来源于stack exchange,提问作者Ramal Abeysekera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:06:49