I want to write a serializable object to file in internal memory. Then, I want to load that object back from that file later. How could I do this in Android?
First of all your object must implement Serializable
. Don't forget to add a serialVersionUID
on the serializable class.
Then if you don't want to save specific field of the object mark it as transient
.
Be sure all fields are serializable.
Next create a file in the internal memory and create an ObjectOutputStream to save your object. If you want to save in a specific folder you can create a path like this:
File path=new File(getFilesDir(),"myobjects");
path.mkdir();
Then you can use that path to save your object:
File filePath =new File(path, "filename");
FileOutputStream fos = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
Reading is similar:
FileInputStream fis = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fis);
MyObjectClass myObject = (MyObjectClass ) in.readObject();
in.close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With