Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎


Problem : How you can save(serialize) an object to Hard Disk or send it to network ?
Solution :
  1.  An object that need to be stored on Hard drive or sent over network need to be serialized. An Object can be serialized only when it implements java.io.Serializable interface.
  2. Use FileOutputStream to open a binary file
  3. Use ObjectOutputStream to convert object into byte stream and connect it to FileOutputStream. To convert an object into byte stream is called serialization and process of converting byte steam back to object is called deserialization 
  4. User ObjectInputStream to read object from a byte stream

Program :

Step 1 - Coding

Create a text file c:/sunilos/Employee.java and copy below contents.

import java.io.Serializable;


 * A program to implement Serializable interface.
public class Employee implements Serializable{
    private int id;
    private String firstName;
    private String lastName;
    private transient String tempValue;
    public Employee(){
        //Default Constructor
    public Employee(int id,String firstName, String lastName){
    public int getId() {
        return id;
    public void setId(int id) {
        this.id = id;
    public String getFirstName() {
        return firstName;
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    public String getLastName() {
        return lastName;
    public void setLastName(String lastName) {
        this.lastName = lastName;
    public Address getAdd() {
        return add;
    public void setAdd(Address add) {
        this.add = add;
    public String getTempValue() {
        return tempValue;
    public void setTempValue(String tempValue) {
        this.tempValue = tempValue;


Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy Employee.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile Employee.java with help of 
    • javac Employee.java command. Command will create Employee.class file in the same folder.
  5. Congratulations!! your serialized object is ready
  6. Now go to next program
<<Previous | Next>>
Namrata Sisodiya,
Aug 19, 2011, 11:08 PM