Core Java: Reading and Writing Object to a File (IOStreams and Exceptions)

IOStreams example: write an employee to a file and read employees from file using java io streams.in this example i also used user defined exceptions. I am providing download link to this example. if free hosing site deletes that file drop your mail id to get this example

download Reading and Writing Object to a file using Serializable and IOStreams

Package structure



Employee.java

package com.jagadeesh.domain;

public interface Employee {

    public Integer getId();

    public void setId(Integer id);

    public String getFirstName();

    public void setFirstName(String firstName);
    
    public String getLastName();

    public void setLastName(String lastName);
    
    public void setEmail(String email);
    
    public String getEmail();

    public int getPriority();

    public void setPriority(int priority);
    
    public String getDesignation();

    public void setDesignation(String designation);

    public String toDisplayString();


}


EmployeeImpl.java

package com.jagadeesh.domain.impl;

import java.io.Serializable;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.utils.EmployeeIO;

public class EmployeeImpl extends EmployeeIO 
 implements Employee,Serializable   {
    
    private static final long serialVersionUID = 1L;
   
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
    private int priority;
    private String designation;
   
    @Override
    public Integer getId() {
        return id;
    }
    
    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String getFirstName() {
        return firstName;
    }
    
    @Override
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    @Override
    public String getLastName() {
        return lastName;
    }
    
    @Override
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String getEmail() {
        return email;
    }

    @Override
    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int getPriority() {
        return priority;
    }

    @Override
    public void setPriority(int priority) {
        this.priority = priority;
    }

    @Override
    public String getDesignation() {
        return designation;
    }

    @Override
    public void setDesignation(String designation) {
        if("CEO".equalsIgnoreCase(designation)){
            setPriority(1);
        }else if("MD".equalsIgnoreCase(designation)){
            setPriority(2);
        }else if("HR".equalsIgnoreCase(designation)){
            setPriority(3);
        }else{
            setPriority(4);
        }
        this.designation = designation;
    }
  
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("EmployeeImpl [id=");
        buffer.append(id);
        buffer.append(", firstName=");
        buffer.append(firstName);
        buffer.append(", lastName=");
        buffer.append(lastName);
        buffer.append(", email=");
        buffer.append(email);
        buffer.append(", priority=");
        buffer.append(priority);
        buffer.append(", designation=");
        buffer.append(designation);
        buffer.append("]");
        return buffer.toString();
    }
 
    @Override
    public boolean equals(Object object){
        if (object == null) return false;
        if (object == this) return true;
        if (this.getClass() != object.getClass())return false;
        Employee employee = (Employee)object;
        if(this.id.equals(employee.getId())
            && this.firstName.equalsIgnoreCase( employee.getFirstName())
            && this.lastName.equalsIgnoreCase( employee.getLastName())
            && this.email.equalsIgnoreCase( employee.getEmail())
            && this.designation.equalsIgnoreCase(employee.getDesignation()))
            return true;
       return false;
    }

    @Override
    public String toDisplayString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.getId());
        buffer.append("\t");
        buffer.append(this.getFirstName());
        buffer.append("\t");
        buffer.append(this.getLastName());
        buffer.append("\t");
        buffer.append(this.getEmail());
        buffer.append("\t");
        buffer.append(this.getDesignation());
        return buffer.toString();
    }    
}


EmployeeService.java

package com.jagadeesh.service;

import java.util.List;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.exceptions.DuplicateIdException;
import com.jagadeesh.exceptions.PersistenceException;

public interface EmployeeService {

    List<Employee> getAll();
    
    List<Employee> readFromFile() throws PersistenceException;

    void addEmployee(Employee employee) throws DuplicateIdException,
            PersistenceException;

}


EmployeeServiceImpl.java

package com.jagadeesh.service.impl;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.exceptions.DuplicateIdException;
import com.jagadeesh.exceptions.PersistenceException;
import com.jagadeesh.service.EmployeeService;

public class EmployeeServiceImpl implements EmployeeService {
    private List<Employee> employees = new ArrayList<Employee>();

    private List<Employee> employeesFromFile = new ArrayList<Employee>();

    public EmployeeServiceImpl() throws PersistenceException {
        this.employees = readFromFile();
    }

    @Override
    public List<Employee> getAll() {
        List<Employee> employees = new ArrayList<Employee>(this.employees);
        return Collections.unmodifiableList(employees);
    }

    @Override
    public void addEmployee(Employee employee) throws DuplicateIdException,
            PersistenceException {
        for (Employee emp : employees) {
            if (emp.getId() == employee.getId())
                throw new DuplicateIdException(employee.getId());
        }
        // saving employee object to file
        writeToFile(employee);
        this.employees.add(employee);
    }

    @Override
    public List<Employee> readFromFile() throws PersistenceException {
        ObjectInputStream objectInputStream = null;
        try {
            File file = new File("c://employees.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            objectInputStream = new ObjectInputStream(new FileInputStream(file));
            while (true) {
                Employee emp = (Employee) objectInputStream.readObject();
                employeesFromFile.add(emp);
            }
        } catch (EOFException e) {

        } catch (FileNotFoundException e) {
            throw new PersistenceException(e);
        } catch (IOException e) {
            throw new PersistenceException(e);
        } catch (ClassNotFoundException e) {
            throw new PersistenceException(e);
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    throw new PersistenceException(e);
                }
            }
        }
        return employeesFromFile;
    }


    private void writeToFile(Employee employee) throws PersistenceException {
        ObjectOutputStream objectOutputStream = null;
        try {
            File outFile = new File("c://employees.txt");
            objectOutputStream = getObjectStream(new FileOutputStream(outFile,
                    true), this.employees.isEmpty());
            objectOutputStream.writeObject(employee);
        } catch (FileNotFoundException e) {
            throw new PersistenceException(e);
        } catch (IOException e) {
            throw new PersistenceException(e);
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    throw new PersistenceException(e);
                }
            }
        }
    }
    
    private static ObjectOutputStream getObjectStream(OutputStream out,
            final boolean isNew) throws IOException {
        return new ObjectOutputStream(out) {
            @Override
            protected void writeStreamHeader() throws IOException {
                if (isNew) {
                    super.writeStreamHeader();
                }
            }
        };
    }

}


EmployeeIO.java

package com.jagadeesh.utils;

import java.util.List;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.domain.impl.EmployeeImpl;


public class EmployeeIO {

    public static Employee read() {
        Employee employee = new EmployeeImpl();
        employee.setId(KeyBoard.readInt("Enter Id :"));
        employee.setFirstName(KeyBoard.read("Enter First Name :"));
        employee.setLastName(KeyBoard.read("Enter Last Name :"));
        employee.setEmail(KeyBoard.read("Enter Email :"));
        employee.setDesignation(KeyBoard.read("Enter Designation :"));        
        return employee;
    }
    
    public static void out(List<Employee> employees) {
        StringBuilder builder = new StringBuilder();
        builder.append("Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n");
        for(int i = 0; i < employees.size(); i++) {
            builder.append(employees.get(i).toDisplayString());
            builder.append("\n");
        }
        System.out.println(builder);
    }
}

KeyBoard.java
package com.jagadeesh.utils;

import java.util.Scanner;

public class KeyBoard {
  
    public static int readInt(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        try {
            int number = Integer.parseInt(scanner.next());
            return number;
        }
        catch(NumberFormatException e) {
            System.out.println("Invalid Number");
            return readInt(message);
        }            
    }
    
    public static String read(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }    
}

DuplicateIdException.java
package com.jagadeesh.exceptions;

public class DuplicateIdException extends Exception {

 private static final long serialVersionUID = 1L;

 private int id;

 public DuplicateIdException(int id) {
  this.id = id;
 }

 public String toString() {
  return "Duplicate Employee Id.. " + id;
 }
}
 
PersistanceException.java
package com.jagadeesh.exceptions;

public class PersistenceException extends Exception {
    
    private static final long serialVersionUID = 1L;

    public PersistenceException() {
        super();
    }
    public PersistenceException(Exception e) {
        super(e);
    }
    public PersistenceException(String message, Exception e) {
        super(message, e);
    }
    
}

EmployeeMain.java
package com.jagadeesh.main;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.exceptions.DuplicateIdException;
import com.jagadeesh.exceptions.PersistenceException;
import com.jagadeesh.service.EmployeeService;
import com.jagadeesh.service.impl.EmployeeServiceImpl;
import com.jagadeesh.utils.EmployeeIO;
import com.jagadeesh.utils.KeyBoard;


public class EmployeeMain {

    public static void main(String[] args) throws PersistenceException {
        int option = 1;
        EmployeeService empService = new EmployeeServiceImpl();
        do {
            Employee employee = EmployeeIO.read();
            try{
                empService.addEmployee(employee);
            }catch(DuplicateIdException e){
                System.out.println("Duplicate Id");
            } catch (PersistenceException e) {
               System.out.println("Persistence error");
            }
            option = KeyBoard.readInt(
                    "Do you want add another employee(1/0) :");
            
        } while(option == 1);
        System.out.println("Reading from file");
        EmployeeIO.out(empService.getAll());
    }
}
Output of the programe

When we run this program first time it creates employees file and all employees will be stored into that file
Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :2
Enter First Name :kumar
Enter Last Name :jagadeesh
Enter Email :k.manne@yahoo.com
Enter Designation :developer
Do you want add another employee(1/0) :0
Reading from file
Id  First Name  Last Name  Email tDesignation
1 jagadeesh kumar mannejkumar@gmail.com developer
2 kumar jagadeesh k.manne@yahoo.com developer

when we run this program second time we read all employee objects from file in EmployeeServiceImpl constructor.after that we will add new employees to that file.
we will get following output when we add one more employee.
Enter Id :3
Enter First Name :myrmidons
Enter Last Name :co.in
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :0

Reading from file
Id  First Name  Last Name  Email tDesignation
1 jagadeesh kumar mannejkumar@gmail.com developer
2 kumar jagadeesh k.manne@yahoo.com developer
3 myrmidons co.in mannejkumar@gmail.com developer

Categories: