簡體   English   中英

FileOutputStream上的java.io.EOFException

[英]java.io.EOFException on FileOutputStream

我有一個類讀取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();時有錯誤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

移動這一行:

fileReader.close();

在你for循環之后。

在Java中,變量的創建只是創建對內存中某個位置的引用。 將從fileReader讀取的對象轉換為學生數組的行為只是創建指向內存中正確位置的指針。 如果您通過關閉fileReader刪除該位置,則刪除studs指向的位置。

檢查students_updated.dat文件的內容。 readObject()函數期望文件包含序列化對象。

該文件是否包含序列化對象? 檢查序列化是否成功,沒有出現任何問題?

如果您嘗試從純文本文件構造數組,則不應使用readObject()。

請訪問此鏈接以獲取有關如何序列化和反序列化數組的示例 - 我可以直接序列化數組...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM