How to deserialize a file back to the original class object [closed]

不打扰是莪最后的温柔 提交于 2019-12-12 04:36:41

问题


I created a class and I periodically save objects of this class to internal storage using Serializable. When I want to retrieve these objects, I use this approach:

for(File i: getFilesDir().listFiles()){
    //Skipped enclosing try-catch block
        FileInputStream fis = openFileInput(i.getName());
        ObjectInputStream ois = new ObjectInputStream(fis);
        SingleWallet theObjectWeWant = ois.readObject();
             }

This results in a compile-time error (Incompatible types). How do I get my class back from the object returned from ois.readObject()? What am I doing wrong?


回答1:


Even when I use listFiles() to get all the files in the directory, they are represented as files, not Card Objects.

That's because they are files, not objects.




回答2:


The mistake I made was failing to cast my newly gotten object to my intended class.

Changing

SingleWallet theObjectWeWant = ois.readObject();

to

SingleWallet theObjectWeWant = (SingleWallet) ois.readObject();

made the difference.

Basically, I should have casted from object to SingleWallet.

I hope this helps someone out there.



来源:https://stackoverflow.com/questions/44198259/how-to-deserialize-a-file-back-to-the-original-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!