开发者

EOFException when readObject in an android app

开发者 https://www.devze.com 2023-03-09 08:45 出处:网络
I use serialization to save data in my android app. Everything works beautifully until a user report he can not open his file.

I use serialization to save data in my android app. Everything works beautifully until a user report he can not open his file.

After examined the file he sent to me, it turned out the problem is an EOFException when readObject().

I opened the .ser file in vim, it is not empty. It looks as normal as other files which can be opened normally.

No surprise happened when the user saved the .ser file.

My questions are:

1. Is it a wrong decision to use serialization in the first place?

2. My code works normally in most of the cases, but I may have missed something which eventually cause this problem.

3. The user said the file is INCREDIBLY important for him, so I really want to find a work around to open this file.

Here is the code how the file is readed:

    FileInputStream f_in = null;
    ObjectInputStream obj_in = null;

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

Here is the code I use for saving a serializable.

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){

            }
    }
}

Here is a code snippet of Block definition:

public class Block implements Serializable{
        private static final long serialVersionUID = -4369689728261781215L;
        private int mType;
        private byte[] mContent;
        private ArrayList<Block&g开发者_C百科t; mChildren = null;
        //... no more attributes.
}


In the code for saving the serializable, where is the exception handled?

I think its safe to assume, because you can't read the file, that an exception was raised while the file was being written. It is doubtful, in my mind, that you will be able to recover the file if you simply closed the outputstream after encountering an error.


EOFException is normal! it just means you got to the end of the object stream. If you get it when reading the first object, the stream has no objects in it. Note that it does have an object output stream header, otherwise you would have got a different exception, so it isn't empty. Just empty of objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号