ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

Serialization in Java

In this post we will learn about Serialization in Java.

Serialization is a mechanism in Java wherein we write object state into file system. It is insecure operation as compare to Object cloning.

Let us go little bit in depth to understand more.

Through this mechanism object can be represented as a sequence of bytes which┬áincludes the object’s data as well as information about the object’s type and the types of data stored in the object. After an object is serialized , the state can be read from the file.

Most interesting and impressive part of this mechanism is that this is platform independent.

Method which is used for Serialization is:

public final void writeObject(Object x) throws IOException

 

Let us take an example:

  1. class A implements Serializable{
  2.  
  3. int i;
  4.  
  5. //Serializable is a marker interface
  6.  
  7. }
  8.  
  9. public class Manager{
  10.  
  11. public static void main(String args[]){
  12.  
  13. A a1=new A();
  14.  
  15. a1.i=1000;
  16.  
  17. File f=new File("demo_serialization.ser") // path of the file
  18.  
  19.  
  20.  
  21. out.writeObject(a1);
  22.  
  23. System.out.println("done");
  24.  
  25. }
  26.  
  27. }

 

Output:

done

 

For reading data from the file we need to deserialize it using the method

 

public final Object readObject() throws IOException, ClassNotFoundException

 

Let us take an example for deserialization :

  1. public class DemoDeserialization{
  2.  
  3. public static void main(String args[]) throws IOException ,ClassNotFOundException {
  4.  
  5. File f=new File("demo_serialization.ser");
  6.  
  7. FileinputStream fis=new FileInputStream(f);
  8.  
  9. ObjectInputStream in=new ObjectinputStream(fis);
  10.  
  11. A a1=(A).in.readObject(); //downcasting
  12.  
  13. System.out.println(a1.i);
  14.  
  15. System.out.println("done");
  16.  
  17. }
  18.  
  19. }

OUTPUT:

1000

done

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!