带有readObject的Java Mysterious EOF异常 [英] Java Mysterious EOF exception with readObject

查看:117
本文介绍了带有readObject的Java Mysterious EOF异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码生成 EOFException 。为什么?

The following code produces an EOFException. Why is that?

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();
            }
        }

StackTrace:

StackTrace:

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 


推荐答案

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

Depends on how many objects your file contains. If it has only one object, you can deserialise in one step.

try {
    Object temp = ois.readObject();
}
catch(Exception e) {
    //handle it
}

这篇关于带有readObject的Java Mysterious EOF异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆