【问题标题】:java.io.EOFException on FileOutputStreamFileOutputStream 上的 java.io.EOFException
【发布时间】:2012-07-06 16:35:18
【问题描述】:

我有一个类可以读取 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

【问题讨论】:

    标签: java arrays fileinputstream objectinputstream eofexception


    【解决方案1】:

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

    文件是否包含序列化对象?检查序列化是否成功,没有任何问题?

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

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

    【讨论】:

    • 对象数组没有序列化是事实。谢谢!
    【解决方案2】:

    移动这一行:

    fileReader.close();
    

    在您的 for 循环之后。

    在 Java 中,创建变量只是创建对内存中某个位置的引用。将从fileReader 读取的对象转换为学生数组的行为只会创建一个指向内存中正确位置的指针。如果您随后通过关闭 fileReader 来删除该位置,那么您将删除 studs 指向的位置。

    【讨论】:

    • 它仍然返回相同的异常。我也在没有fileReader.close() 的情况下尝试了它,但它没有工作的机会。
    • 您确定您的文件中有内容吗?这些数据是如何编码的?
    • 是的,里面有一个student[],我用system.out.print(); 让它出现在控制台中,它确实有内容
    • 顺便说一下写对象之前
    猜你喜欢
    • 2014-08-20
    • 1970-01-01
    • 2021-05-17
    • 2019-05-10
    • 2018-06-14
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    相关资源
    最近更新 更多