0


我使用序列化将数据保存在我的 android 应用程序中。一切都很顺利,直到用户报告他无法打开他的文件。
在检查了他发送给我的文件后,发现问题是 readObject() 时出现 EOFException。

我在 vim 中打开了 .ser 文件,它不是空的。它看起来和其他可以正常打开的文件一样正常。
当用户保存 .ser 文件时,不出意外。

我的问题是:
1. 首先使用序列化是一个错误的决定吗?
2. 我的代码在大多数情况下都能正常工作,但我可能遗漏了一些最终导致此问题的内容。
3. 用户说这个文件对他来说非常重要,所以我真的很想找到一个解决方法来打开这个文件。

以下是如何读取文件的代码:

    FileInputStream f_in = null;
    ObjectInputStream obj_in = null;

    f_in = new FileInputStream(fileName);
    obj_in = new ObjectInputStream (f_in);
    mBlock = (Block)obj_in.readObject();

这是我用于保存可序列化的代码。

saveObjToFile(mBlock, mFileName);

static void saveObjToFile(Serializable object, String fileName)                     
throws IOException{
    FileOutputStream f_out = null;
    ObjectOutputStream obj_out  = null;
    try{
        File note_file = new File(fileName);
        f_out = new FileOutputStream(note_file);
        obj_out = new ObjectOutputStream (f_out);
        obj_out.writeObject(object);
        obj_out.flush();
        obj_out.close();
    }finally{
        if (obj_out != null)
            try{
                obj_out.close();
            }catch(IOException e){

            }
        if (f_out != null)
            try{
                f_out.close();
            }catch(IOException e){

            }
    }
}

这是块定义的代码片段:

public class Block implements Serializable{
        private static final long serialVersionUID = -4369689728261781215L;
        private int mType;
        private byte[] mContent;
        private ArrayList<Block> mChildren = null;
        //... no more attributes.
}
4

2 回答 2

0

在保存可序列化的代码中,异常在哪里处理?

我认为可以安全地假设,因为您无法读取文件,因此在写入文件时引发了异常。在我看来,如果您在遇到错误后简单地关闭输出流,您是否能够恢复文件是值得怀疑的。

于 2011-05-28T04:17:32.217 回答
0

EOFException 是正常的!它只是意味着你到了对象流的末尾。如果在读取第一个对象时得到它,则流中没有对象。请注意,它确实有一个对象输出流标头,否则您会遇到不同的异常,因此它不为空。只是空的对象。

于 2011-05-28T23:55:26.373 回答