问题
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