www.000webhost.com
/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Serialization in Java


Serialization in Java

Core Java

The process of writing state of an object to a file is called Serialization.


What is Java Serialization?



Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.

Serializable is a marker interfaces that tells the JVM is can write out the state of the object to some stream (basically read all the members, and write out their state to a stream, or to disk or something). The default mechanism is a binary format. You can also use it to clone things, or keep state between invocations, send objects across the network etc.


How do you serialize?



When you want to serialize an object, that respective class should implement the marker interface serializable. It just informs the compiler that this java class can be serialized. You can tag properties that should not be serialized as transient. You open a stream and write the object into it. Java API takes care of the serialization protocol and persists the java object in a file in conformance with the protocol. De-serialization is the process of getting the object back from the file to its original form.



Notice that for a class to be serialized successfully, two conditions must be met:


Example :- how to serialize and de-serialize

 

package com.javaEssential.example;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
class SerializationBox implements Serializable {
 
  private byte serializableProp = 10;
 
  public byte getSerializableProp() {
    return serializableProp;
  }
}
 
public class SerializationSample {
 
  public static void main(String args[]) throws IOException,
      FileNotFoundException, ClassNotFoundException {
 
    SerializationBox serialB = new SerializationBox();
    serialize("serial.out", serialB);
    SerializationBox sb = (SerializationBox) deSerialize("serial.out");
    System.out.println(sb.getSerializableProp());
  }
 
  public static void serialize(String outFile, Object serializableObject)
      throws IOException {
    FileOutputStream fos = new FileOutputStream(outFile);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(serializableObject);
  }
 
  public static Object deSerialize(String serilizedObject)
      throws FileNotFoundException, IOException, ClassNotFoundException {
    FileInputStream fis = new FileInputStream(serilizedObject);
    ObjectInputStream ois = new ObjectInputStream(fis);
    return ois.readObject();
  }
}

Another Example on serialization :-


import java.io.*;
 
public class ObjectSerializationTest {
   public static void main(String[] args) {
      String filename = "object.ser";
      int numObjs = 5;
 
      // Write objects
      try (ObjectOutputStream out =
              new ObjectOutputStream(
                 new BufferedOutputStream(
                    new FileOutputStream(filename)))) {
 
         // Create an array of 10 MySerializedObjects with ascending numbers
         MySerializedObject[] objs = new MySerializedObject[numObjs];
         for (int i = 0; i < numObjs; ++i) {
            objs[i] = new MySerializedObject(0xAA + i); // Starting at AA
         }
         // Write the objects to file, one by one.
         for (int i = 0; i < numObjs; ++i) {
            out.writeObject(objs[i]);
         }
         // Write the entire array in one go.
         out.writeObject(objs);
         out.flush();
      } catch (IOException ex) {
         ex.printStackTrace();
      }
 
      // Read raws bytes and print in Hex
      try (BufferedInputStream in =
              new BufferedInputStream(
                 new FileInputStream(filename))) {
         int inByte;
         while ((inByte = in.read()) != -1) {
            System.out.printf("%02X ", inByte);   // Print Hex codes
         }
         System.out.printf("%n%n");
      } catch (IOException ex) {
         ex.printStackTrace();
      }
 
      // Read objects
      try (ObjectInputStream in =
              new ObjectInputStream(
                 new BufferedInputStream(
                    new FileInputStream(filename)))) {
         // Read back the objects, cast back to its original type.
         MySerializedObject objIn;
         for (int i = 0; i < numObjs; ++i) {
            objIn = (MySerializedObject)in.readObject();
            System.out.println(objIn.getNumber());
         }
         MySerializedObject[] objArrayIn;
         objArrayIn = (MySerializedObject[])in.readObject();
         for (MySerializedObject o : objArrayIn) {
            System.out.println(o.getNumber());
         }
      } catch (ClassNotFoundException|IOException ex) {  // JDK 7
         ex.printStackTrace();
      }
   }
}
 
class MySerializedObject implements Serializable {
   private int number;
 
   public MySerializedObject(int number) {
      this.number = number;
   }
 
   public int getNumber() {
      return number;
   }
}
 _____________________________________________________
Output :-

AC ED 00 05 73 72 00 12 4D 79 53 65 72 69 61 6C 69 7A 65 64 4F 62 6A 65 
63 74 1F 7B 91 BD 02 1C DC 30 02 00 01 49 00 06 6E 75 6D 62 65 72 78 70 
00 00 00 AA 73 71 00 7E 00 00 00 00 00 AB 73 71 00 7E 00 00 
00 00 00 AC 73 71 00 7E 00 00 00 00 00 AD 73 71 00 7E 00 00 
00 00 00 AE 75 72 00 15 5B 4C 4D 79 53 65 72 69 61 6C 69 7A 65 64 4F 62 
6A 65 63 74 3B 13 95 A0 51 BC 86 75 38 02 00 00 78 70 00 00 00 05 71 00 
7E 00 01 71 00 7E 00 02 71 00 7E 00 03 71 00 7E 00 04 71 00 7E 00 05


transient & static





Click here to access OOp's Concept

feel free to ask any of your doubts