Powered by Blogger.

What is Serialization? Write a Simple program in java using Serialization?

>> Saturday, April 16, 2011

"Serialization is the process of converting the data(Objects) into stream of bytes and storing in to the files or database."

Serialization in Java with Simple program_JavabynataraJ

We can do the Serialization process by implementing Serializable interface.

class SerialDemo implements java.io.Serializable.

The above step tells the compiler that you are going to implement serialization.
Which basically means that the object is going to be saved or persisted.

use FileOutputStream class and ObjectOutputStream class.

FileOutuptStream Creates an output file stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be write using an ObjectOutputStream.

Save the file using
writeObject(obj);

Program for Serialization

What if you have something top secret, like your password which should not be saved. You mark it as transient!

transient int i;

Create a class Employee to collect information.

package com.javabynataraj.iopack;

class Employee implements java.io.Serializable {
   
 public String name;
 public String address;
 public transient int SSN;
 public int number;

 public void mailCheck() {
    System.out.println("Mailing a check to " + name + " " + address);
  }
}

then create a main class to persist the Employee details in a file.

package com.javabynataraj.iopack;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Serial {
 public static void main(String[] args) {
  Employee e = new Employee();
  e.name = "Muralidhar";
  e.address = "JavabynataraJ,SatyaTechnologies";
  e.SSN = 11111;
  e.number = 101;
  try {
   System.out.println("Before Serialization");
   FileOutputStream fileOut = new FileOutputStream("employee.ser");
   ObjectOutputStream out = new ObjectOutputStream(fileOut);
   out.writeObject(e);
   out.close();
   fileOut.close();
   System.out.println("End of Serialization");
  } catch (IOException i){
   i.printStackTrace();
  }
 }
}

About Author

My Photo
GeekDude
Hi, this is Muralidhar from Chennai.I like blogging on some known things. Trying to provide some basic information for java beginners.
View my complete profile

Random Posts

© javabynataraj.blogspot.com from 2009 - 2014. All rights reserved.