Java Serialization

INTRODUCTION TO JAVA OBJECT SERIALIZATION

Java object serialization is used to persist Java objects to a file, database, network, process or any other system. Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of bytes can then be read at a later time, or in another environment, to recreate the original objects.
Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the state from being written to the stream and from being restored during deserialization. Java provides classes to support writing objects to streams and restoring objects from streams. Only objects that support the java.io.Serializable interface or the java.io.Externalizable interface can be written to streams.
public interface Serializable
  • The Serializable interface has no methods or fields. (Marker Interface)
  • Only objects of classes that implement java.io.Serializable interface can be serialized or deserialized

TRANSIENT FIELDS AND JAVA SERIALIZATION

The transient keyword is a modifier applied to instance variables in a class. It specifies that the variable is not part of the persistent state of the object and thus never saved during serialization.
You can use the transient keyword to describe temporary variables, or variables that contain local information,
such as a process ID or a time lapse.

INPUT AND OUTPUT OBJECT STREAMS

ObjectOutputStream is the primary output stream class that implements the ObjectOutput interface for serializing objects. ObjectInputStream is the primary input stream class that implements the ObjectInput interface for deserializing objects.
These high-level streams are each chained to a low-level stream, such as FileInputStream or FileOutputStream.
The low-level streams handle the bytes of data. The writeObject method saves the state of the class by writing the individual fields to the ObjectOutputStream. The readObject method is used to deserialize the object from
the object input stream.
Case 1: Below is an example that demonstrates object Serialization into a File
PersonDetails is the bean class that implements the Serializable interface
import java.io.Serializable;
public class PersonDetails implements Serializable {

 private String name;
 private int age;
 private String sex;
 public PersonDetails(String name, int age, String sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSex() {
  return sex;
 }
 public void setSex(String sex) {
  this.sex = sex;
 }
}
GetPersonDetails is the class that is used to Deserialize object from the File (person.txt).
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
public class GetPersonDetails {

 public static void main(String[] args) {
  String filename = "person.txt";
  List pDetails = null;
  FileInputStream fis = null;
  ObjectInputStream in = null;
  try {
   fis = new FileInputStream(filename);
   in = new ObjectInputStream(fis);
   pDetails = (ArrayList) in.readObject();
   in.close();
  } catch (IOException ex) {
   ex.printStackTrace();
  } catch (ClassNotFoundException ex) {
   ex.printStackTrace();
  }
  // print out the size
  System.out.println("Person Details Size: " + pDetails.size());
  System.out.println();
 }
}
PersonPersist is the class that is used to serialize object into the File (person.txt).
public class PersonPersist {

 public static void main(String[] args) {
  String filename = "person.txt";
  PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
  PersonDetails person2 = new PersonDetails("bob", 12, "Male");
  PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
  List list = new ArrayList();
  list.add(person1);
  list.add(person2);
  list.add(person3);
  FileOutputStream fos = null;
  ObjectOutputStream out = null;
  try {
   fos = new FileOutputStream(filename);
   out = new ObjectOutputStream(fos);
   out.writeObject(list);
   out.close();
   System.out.println("Object Persisted");
  } catch (IOException ex) {
   ex.printStackTrace();
  }
 }
}
——————————————————————————–
Case 2: Below is an example that demonstrates object Serialization into the database
PersonDetails remains the same as shown above
GetPersonDetails remains the same as shown above
   Create SerialTest Table
   create table SerialTest(
   name BLOB,
   viewname VARCHAR2(30)
   );
PersonPersist is the class that is used to serialize object into the into the Database Table SerialTest.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {

 static String userid = "scott", password = "tiger";
 static String url = "jdbc:odbc:bob";
 static int count = 0;
 static Connection con = null;
 public static void main(String[] args) {
  Connection con = getOracleJDBCConnection();
  PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
  PersonDetails person2 = new PersonDetails("bob", 12, "Male");
  PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
  PreparedStatement ps;
  try {
   ps = con
   .prepareStatement("INSERT INTO SerialTest VALUES (?, ?)");
   write(person1, ps);
   ps.execute();
   write(person2, ps);
   ps.execute();
   write(person3, ps);
   ps.execute();
   ps.close();
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("SELECT * FROM SerialTest");
   while (rs.next()) {
    Object obj = read(rs, "Name");
    PersonDetails p = (PersonDetails) obj;
    System.out.println(p.getName() + "\t" + p.getAge() + 
                                 "\t" + p.getSex());
   }
   rs.close();
   st.close();
  } catch (Exception e) {
  }
 }
 public static void write(Object obj, PreparedStatement ps)
   throws SQLException, IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oout = new ObjectOutputStream(baos);
  oout.writeObject(obj);
  oout.close();
  ps.setBytes(1, baos.toByteArray());
  ps.setInt(2, ++count);
 }
 public static Object read(ResultSet rs, String column)
   throws SQLException, IOException, ClassNotFoundException {
  byte[] buf = rs.getBytes(column);
  if (buf != null) {
   ObjectInputStream objectIn = new ObjectInputStream(
     new ByteArrayInputStream(buf));
   return objectIn.readObject();
  }
  return null;
 }
 public static Connection getOracleJDBCConnection() {
  try {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  } catch (java.lang.ClassNotFoundException e) {
   System.err.print("ClassNotFoundException: ");
   System.err.println(e.getMessage());
  }
  try {
   con = DriverManager.getConnection(url, userid, password);
  } catch (SQLException ex) {
   System.err.println("SQLException: " + ex.getMessage());
  }
  return con;
 }
}
——————————————————————————–
Case 3: Below is an example that demonstrates object Serialization into the database using Base 64 Encoder
PersonDetails remains the same as shown above
GetPersonDetails remains the same as shown above
  Create SerialTest Table
  create table SerialTest(
  name BLOB,
  viewname VARCHAR2(30)
  );
PersonPersist is the class that is used to serialize object into the Database Table SerialTest
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {

 static String userid = "scott", password = "tiger";
 static String url = "jdbc:odbc:bob";
 static int count = 0;
 static Connection con = null;
 static String s;
 public static void main(String[] args) {
  Connection con = getOracleJDBCConnection();
  PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
  PersonDetails person2 = new PersonDetails("bob", 12, "Male");
  PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
  PreparedStatement ps;
  try {
   ps = con
   .prepareStatement("INSERT INTO SerialTest VALUES (?, ?)");
   write(person1, ps);
   ps.execute();
   write(person2, ps);
   ps.execute();
   write(person3, ps);
   ps.execute();
   ps.close();
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("SELECT * FROM SerialTest");
   while (rs.next()) {
    Object obj = read(rs, "Name");
    PersonDetails p = (PersonDetails) obj;
    System.out.println(p.getName() + "\t" + p.getAge() + 
                                "\t" + p.getSex());
   }
   rs.close();
   st.close();
  } catch (Exception e) {
  }
 }
 public static void write(Object obj, PreparedStatement ps)
   throws SQLException, IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oout = new ObjectOutputStream(baos);
  oout.writeObject(obj);
  oout.close();
  byte[] buf = baos.toByteArray();
  s = new sun.misc.BASE64Encoder().encode(buf);
  ps.setString(1, s);
  // ps.setBytes(1, Base64.byteArrayToBase64(baos.toByteArray()));
  ps.setBytes(1, baos.toByteArray());
  ps.setInt(2, ++count);
 }
 public static Object read(ResultSet rs, String column)
   throws SQLException, IOException, ClassNotFoundException {
  byte[] buf = new sun.misc.BASE64Decoder().decodeBuffer(s);
  // byte[] buf = Base64.base64ToByteArray(new
  // String(rs.getBytes(column)));
  if (buf != null) {
   ObjectInputStream objectIn = new ObjectInputStream(
     new ByteArrayInputStream(buf));
   Object obj = objectIn.readObject(); // Contains the object
   PersonDetails p = (PersonDetails) obj;
   System.out.println(p.getName() + "\t" + p.getAge() + "\t"
     + p.getSex());
  }
  return null;
 }
 public static Connection getOracleJDBCConnection() {
  try {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  } catch (java.lang.ClassNotFoundException e) {
   System.err.print("ClassNotFoundException: ");
   System.err.println(e.getMessage());
  }
  try {
   con = DriverManager.getConnection(url, userid, password);
  } catch (SQLException ex) {
   System.err.println("SQLException: " + ex.getMessage());
  }
  return con;
 }
}
Below is a program that shows the serialization of a JButton object to a file and a Byte Array Stream. As before theobject to be serialized must implement the Serializable interface. PersonDetails is the bean class that implements the Serializable interface
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ObjectSerializationExample {

 public static void main(String args[]) {
  try {
   Object object = new javax.swing.JButton("Submit");
   // Serialize to a file namely "filename.dat"
   ObjectOutput out = new ObjectOutputStream(
     new FileOutputStream("filename.dat"));
   out.writeObject(object);
   out.close();
   // Serialize to a byte array
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   out = new ObjectOutputStream(bos);
   out.writeObject(object);
   out.close();
   // Get the bytes of the serialized object
   byte[] buf = bos.toByteArray();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
Download Object Serialization Source code

No comments:

Post a Comment