Android ObjectInputStream and ObjectOutputstream snippet

At first, make your object serializable and let the IDE (in my case Eclipse) generate a serialVersionUID for you:

public class Post implements Serializable{

	private static final long serialVersionUID = 7884946435027239199L;

	public String firstname;

	public String lastname;

}

Writing to files with serialization and writing objects to file:

FileOutputStream fileOutputStream = openFileOutput("personobject", Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream= new ObjectOutputStream(fileOutputStream );
objectOutputStream.writeObject(yourObject);
objectOutputStream.close();

Reading files with serialization and get it as object:

FileInputStream fileInputStream = openFileInput("personobject");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Person person = (Person)objectInputStream.readObject();

Thats it!

 

2 thoughts on “Android ObjectInputStream and ObjectOutputstream snippet”

Leave a Reply

Your email address will not be published. Required fields are marked *