Example & Tutorial understanding programming in easy ways.

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:

student.java:

package javatest.com

import java.io.Serializable;

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;

}

//@Override

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();

}

}

 

objectex.java

package javatest.com;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

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);

System.out.println(st);

}

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");

objectIn.close();

return obj;

} catch (Exception ex) {

ex.printStackTrace();

return null;

}}}

Read More →