如何反序列化文件回到原始类对象 [英] How to deserialize a file back to the original class object
本文介绍了如何反序列化文件回到原始类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个类,并使用Serializable将此类的对象定期保存到内部存储中。当我想检索这些对象时,我使用这种方法:
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();
}
这会导致编译时错误(类型不兼容)。如何从 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?
推荐答案
我犯的错误是未能将新获得的对象转换为预期的类。
The mistake I made was failing to cast my newly gotten object to my intended class.
更改
SingleWallet theObjectWeWant = ois.readObject();
到
SingleWallet theObjectWeWant = (SingleWallet) ois.readObject();
有所作为。
基本上,我本该将对象从对象投射到SingleWallet。
Basically, I should have casted from object to SingleWallet.
我希望这可以帮助某个人。
I hope this helps someone out there.
这篇关于如何反序列化文件回到原始类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文