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

Java读取文件对象时抛出EOFException问题求助

解决读取对象时中途触发EOFException的问题

问题根源

你的代码存在两个关键问题,导致读取中途触发EOFException:

  1. 写入时重复关闭输出流
    你在try-with-resources块中手动调用了out.close(),但try-with-resources会在代码块结束时自动关闭资源。重复关闭会导致BufferedOutputStream中的缓冲数据未完全写入文件,文件实际存储的对象数量少于预期,读取到中途就没有数据,进而触发EOFException。

  2. 读取循环逻辑不符合API规范
    ObjectInputStream.readObject()在到达文件末尾时不会返回null,而是直接抛出EOFException。你的while循环条件(lol = (Person)in.readObject())!= null本身就错误,即便文件完整,读完所有对象后也会触发异常,而非正常退出循环。

修复后的代码

写入部分修复

移除手动调用的out.close(),让try-with-resources自动处理关闭和缓冲刷新:

//WRITING
try ( ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream (new FileOutputStream("object.txt")))) {
    for (int i = 0; i < people.length; i++) {
        out.writeObject(people[i]);
    }
    // 移除out.close(),try-with-resources会自动完成关闭与缓冲写入
} catch (IOException e) {
    e.printStackTrace();
}

读取部分修复

方案一:用EOFException作为循环结束标志(常规处理方式)

try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream( new FileInputStream("object.txt")))){
    Person lol;
    while (true) {
        try {
            lol = (Person)in.readObject();
            System.out.println(lol);
        } catch (EOFException e) {
            // 到达文件末尾,退出循环
            break;
        }
    }
} catch(IOException | ClassNotFoundException e){
    e.printStackTrace();
}

方案二:写入时先保存对象总数,读取时按次数循环(更可控)

写入部分修改:

try ( ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream (new FileOutputStream("object.txt")))) {
    // 先写入对象总数
    out.writeInt(people.length);
    for (int i = 0; i < people.length; i++) {
        out.writeObject(people[i]);
    }
} catch (IOException e) {
    e.printStackTrace();
}

读取部分修改:

try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream( new FileInputStream("object.txt")))){
    // 先读取对象总数
    int total = in.readInt();
    for (int i = 0; i < total; i++) {
        Person lol = (Person)in.readObject();
        System.out.println(lol);
    }
} catch(IOException | ClassNotFoundException e){
    e.printStackTrace();
}

关键注意事项

  • 所有涉及序列化的类(Person、Professor、TA、Student)必须实现Serializable接口,否则写入时会抛出NotSerializableException,这是容易忽略的隐藏问题。
  • 始终用try-with-resources管理流资源,避免手动关闭导致的异常或数据丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:01:37