How to store and read objects from a file in java?.

How to store and read objects from a file in java?.

Basically, to read an Object from a file, one should follow these steps:

a)Open a FileInputStream to the file that youíve stored the Object to.
b)Open a ObjectInputStream to the above FileInpoutStream.
c)Use readObject method of ObjectInputStream class to read the Object from the file.
d)The above method returns an Object of type Object. So you have to cast it to the original type to use it properly.
Letís see the code snippets that follow:



public class Student implements Serializable {

//default serialVersion id

private static final long serialVersionUID = 1L;

private String first_name;

private String last_name;

private int age;

public Student(String fname, String lname, int age){

this.first_name = fname;

this.last_name = lname;

this.age = age;


public void setFirstName(String fname) {

this.first_name = fname;


public String getFirstName() {

return this.first_name;


public void setLastName(String lname) {

this.first_name = lname;


public String getLastName() {

return this.last_name;


public void setAge(int age) {

this.age = age;  }

public int getAge() {

return this.age;



public String toString() {

return new StringBuffer(" First Name : ").append(this.first_name)

.append(", Last Name : ").append(this.last_name).append(", Age : ").append(this.age).toString();








public class Objectex{

private static final String filepath="C:\\Users\\javatest\\Desktop\\obj";

public static void main(String args[]) {

Objectex objectIO = new Objectex();

//Read object from file

Student st = (Student) objectIO.ReadObjectFromFile(filepath);



public Object ReadObjectFromFile(String filepath) {

try {

FileInputStream fileIn = new FileInputStream(filepath);

ObjectInputStream objectIn = new ObjectInputStream(fileIn);

Object obj = objectIn.readObject();

System.out.println("The Object has been read from a file");


return obj;

} catch (Exception ex) {


return null;


Read More →