Sunday, 24 April 2016

How to read and write an Object to file ?


Write an Object to file
Java object can be written into a file for future access, this is called serialization.

  • Implement the Serializable interface
  • Use ObjectOutputStream.writeObject to write the object into a file.

Example
Address address = new Address("F-31A", "New market", "New Delhi");
FileOutputStream fout = new FileOutputStream("c:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(address);

oos.close();


Read an Object from file
The deserialization process is quite similar with the serialization

  • Use ObjectInputStream.writeObject to read the content of the file and convert it back to Java object

Example
FileInputStream fin = new FileInputStream("c:\\address.ser");
ObjectInputStream ois = new ObjectInputStream(fin);
Address address = (Address) ois.readObject();

ois.close();

No comments:

Post a Comment

Note: only a member of this blog may post a comment.