store and read objects from a file java program

Example:

Employee.java

package com.w3spoint;
 
import java.io.Serializable;
 
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    private String empName;
    private int empId;
    private String salary;
 
    public Employee(String empName, int empId, String salary){
        this.empName = empName;
        this.empId = empId;
        this.salary = salary;
    }
 
    public String toString(){
        return "Emp Name: "+empName +", Emp Id: "
        		+empId+", Salary: "+salary;
    }
 
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public int getEmpId() {
		return empId;
	}
	public void setEmpId(int empId) {
		this.empId = empId;
	}
	public String getSalary() {
		return salary;
	}
	public void setSalary(String salary) {
		this.salary = salary;
	}
}

ObjectFileProcessing.java

package com.tutorialspointexamples;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
 
public class ObjectFileProcessing {
     public void storeObject(Employee emp){        
        OutputStream ops = null;
        ObjectOutputStream objOps = null;
        try {
            ops = new FileOutputStream("EmpFile.txt");
            objOps = new ObjectOutputStream(ops);
            objOps.writeObject(emp);
            objOps.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }         
    }
 
    public void displayObjects(){         
        InputStream fileIs = null;
        ObjectInputStream objIs = null;
        try {
            fileIs = new FileInputStream("EmpFile.txt");
            objIs = new ObjectInputStream(fileIs);
            Employee emp = (Employee) objIs.readObject();
            System.out.println(emp);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }   
}

FileObjectTest.java

package com.tutorialspointexamples;
 
public class FileObjectTest {
  public static void main(String args[]){
      ObjectFileProcessing objectFileProcessing = new ObjectFileProcessing();
      Employee e1 = new Employee("Vikas",5,"50000");
      objectFileProcessing.storeObject(e1);
      objectFileProcessing.displayObjects();
  }
}

Output:

Emp Name: Vikas, Emp Id: 5, Salary: 50000

Download this example.

Content Protection by DMCA.com
Please Share