Tuesday, March 29, 2016

Java I/O Examples : How To Read An Object From File

Intro


This examples will demonstrates how to read a Java object from file which means deserialization.

Examples


Employee.java

package com.freesamplecode.java.io;

import java.io.Serializable;
import java.util.Date;

public class Employee implements Serializable{
 /**
  * 
  */
 private static final long serialVersionUID = 8836890329708390627L;
 
 private long id;
 private String name;
 private String sex;
 private String placeOfBirth;
 private Date dateOfBirth;
 
 public long getId() {
  return id;
 }
 
 public void setId(long id) {
  this.id = id;
 }
 
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public String getSex() {
  return sex;
 }
 
 public void setSex(String sex) {
  this.sex = sex;
 }
 
 public String getPlaceOfBirth() {
  return placeOfBirth;
 }
 
 public void setPlaceOfBirth(String placeOfBirth) {
  this.placeOfBirth = placeOfBirth;
 }
 
 public Date getDateOfBirth() {
  return dateOfBirth;
 }
 
 public void setDateOfBirth(Date dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }
 
}

ReadObjectFromFileDemo.java

public class ReadObjectFromFileDemo {
 public static void main(String[] args){
  try {
   FileInputStream fis = new FileInputStream("c:/TEMP/employee.ser");
   ObjectInputStream ois = new ObjectInputStream(fis);
   Employee employee = (Employee) ois.readObject();
   
   System.out.println("Read Employee data...");
   System.out.println("ID : " +employee.getId());
   System.out.println("Name : " +employee.getName());
   System.out.println("Place of Birth : " +employee.getPlaceOfBirth());
   System.out.println("Date of Birth : " +employee.getDateOfBirth());
   System.out.println("Gender : " +employee.getSex());
   
   ois.close();
  } catch (FileNotFoundException e) {
   System.err.println("File not found");
   e.printStackTrace();
  } catch (IOException e) {
   System.err.println("Error when accessing file");
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}

Output


Read Employee data...
ID : 879829
Name : Nursalim
Place of Birth : Brebes
Date of Birth : Tue Mar 29 15:32:25 ICT 2016
Gender : M

Screenshot

How To Read An Object From File In Java


Related Posts:

0 comments: