11

以下代码生成一个EOFException. 这是为什么?

public static Info readInfoDataFromFile(Context context) {
    Info InfoData = null;
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    Object object = null;

    if (context.getFileStreamPath("InfoFile.dat").exists()) {
        try {
            fis = context.openFileInput("InfoFile.dat");
            ois = new ObjectInputStream(fis);
            Object temp;
            try {
                // here it throws EOF exception in while loop 
                while ((temp = ois.readObject()) != null) {
                    object = temp;
                }
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            } catch (EOFException eof) {
                eof.printStackTrace();
            } catch (FileNotFoundException fnfe) {
                fnfe.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

堆栈跟踪:

03-07 14:29:01.996: WARN/System.err(13984): java.io.EOFException
03-07 14:29:01.996: WARN/System.err(13984):     at java.io.DataInputStream.readByte(DataInputStream.java:131)
03-07 14:29:01.996: WARN/System.err(13984):     at java.io.ObjectInputStream.nextTC(ObjectInputStream.java:628)
03-07 14:29:01.996: WARN/System.err(13984):     at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:907)
03-07 14:29:01.996: WARN/System.err(13984):     at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)03-07 14:29:01.996: WARN/System.err(13984):     at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
03-07 14:29:01.996: WARN/System.err(13984):     at 
4

5 回答 5

9

取决于您的文件包含多少对象。如果它只有一个对象,您可以一步反序列化。

try {
    Object temp = ois.readObject();
}
catch(Exception e) {
    //handle it
}
于 2011-03-07T09:30:47.357 回答
8

首先,仅当您在创建流时写入流readObject()时才返回。如果流中没有更多数据,它将抛出一个.nullnullEOFException

如果您不期望 EOF,原因可能是流已损坏。如果您在向其写入数据后忘记关闭它,则可能会发生这种情况。

于 2011-03-07T09:43:23.833 回答
5

我有同样的神秘EOFException,它只是对象类的路径发送ObjectOutputStreamObjectInputStream. 它们必须具有相同的路径(相同的包名,当然还有相同的类名)。

于 2013-04-18T10:26:39.743 回答
2

readObject()on的定义ObjectInputStream没有指定它会null在到达流的末尾时返回。相反,如果您尝试读取超出文件末尾的附加对象,则会引发异常。

于 2011-03-07T09:38:03.997 回答
0

我收到此错误是因为OutputStream.write()用于写入intInputStream.readInt()读取。

但是,根据文档OutputStream.write编写 a byte(put 接受intas 参数),所以我需要使用OutputStream.writeInt.

于 2020-07-31T09:15:42.610 回答