Tuesday, March 29, 2016

Java I/O Examples : How To Write An Object To File

Intro


This examples will demonstrates how to write a Java object into file using serialization method. To use serialization method, your Java class have to implement the Serializable interface.

Examples


Employee.java

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

WriteObjectToFileDemo.java

public class WriteObjectToFileDemo {
 public static void main(String[] args){
  //create an Employee object
  Employee employee = new Employee();
  employee.setId(879829);
  employee.setName("Nursalim");
  employee.setPlaceOfBirth("Brebes");
  employee.setDateOfBirth(new Date());
  employee.setSex("M");
  
  try {
   FileOutputStream fos = new FileOutputStream("c:/TEMP/employee.ser");
   
   ObjectOutputStream oos = new ObjectOutputStream(fos);
   oos.writeObject(employee);
   oos.close();
   
   System.out.println("Done!, Successfully write object to file...");
  } catch (FileNotFoundException e) {
   System.err.println("File not found");
   e.printStackTrace();
  } catch (IOException e) {
   System.err.println("Error encountered...");
   e.printStackTrace();
  }
  
 }
}

Output


Done!, Successfully write object to file...

Screenshot


How To Write An Object To File In Java

0 comments: