Thursday, February 09, 2017

Serialize and Deserialize Object in java

Sample Data Class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package sample.test;

import java.util.Vector;

public class MyXML implements java.io.Serializable {

 String name;
 String value;
 Vector subtree = new Vector();

 public MyXML() {
 }

 public void insert(MyXML x) {
  subtree.addElement(x);
 }

 static final long serialVersionUID = 1L;
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package sample.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeTest {
 public static void main1(String[] args)
 {
  try
  {
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("empInfo.ser"));
      MyXML emp = new MyXML();
   emp.name = "test";
   emp.value = "1";
      //Serialize the object
      oos.writeObject(emp);
      oos.close();
  } catch (Exception e)
  {
      System.out.println(e);
  }

 }

 public static void main(String[] args) {
  try {
   ObjectInputStream ooi = new ObjectInputStream(new FileInputStream(
     "empInfo.ser"));
   // Read the object back
   MyXML readEmpInfo = (MyXML) ooi.readObject();
   System.out.println(readEmpInfo.name);
   System.out.println(readEmpInfo.value);
   ooi.close();
  } catch (Exception e) {
   System.out.println(e);
  }

 }
}