gpt4 book ai didi

FileOutputStream 上的 java.io.EOFException

转载 作者:行者123 更新时间:2023-12-02 07:42:47 25 4
gpt4 key购买 nike

我有一个类读取 Student[] 数组对象的写入输出

这是代码

import java.io.*;

// I use this class to read the final ouput "students_updated.dat"
public class StudentArrayObjectFileReader {

public static void main(String[] args) {
try {
ObjectInputStream fileReader = new ObjectInputStream(new FileInputStream("students_updated.dat"));
Student[] studs = (Student[]) fileReader.readObject();
fileReader.close();

// List the records in console
for (int i = 0; i < studs.length; i++) {
System.out.printf("%7d %-35s %-5s %1d %-6s%n",studs[i].getID(), studs[i].getName(), studs[i].getCourse(), studs[i].getYr(), studs[i].getGender());
}
} catch (FileNotFoundException fnfe) {

fnfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

问题是读取 Student[] Studs = (Student[]) fileReader.readObject(); 时出错

如此处所述

java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2571)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at StudentArrayObjectFileReader.main(StudentArrayObjectFileReader.java:9)

知道可能是什么问题吗?提前致谢..

这就是students_updated.dat的编写方式

    public void saveStudentArray() { // studs print to student_updated.dat
try{
output.writeObject(studs); // write the final studs
output.close();
}catch(Exception e){
e.printStackTrace();
}
}

在该方法所在的构造函数中声明其 ObjectInputStream

最佳答案

检查students_updated.dat 文件的内容。 readObject() 函数期望文件包含序列化对象。

文件是否包含序列化对象?检查序列化是否成功且没有任何错误?

如果您尝试从纯文本文件构造数组,则不应使用 readObject()。

访问此链接以获取有关如何序列化和反序列化数组的示例 - Can I serialize an array directly...

关于FileOutputStream 上的 java.io.EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11366238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com