Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object.
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.
Code for serialization of a java class :
Data.java
package com.codetalk.serialization; import java.io.Serializable; public class Data implements Serializable { private static final long serialVersionUID = 1L; private String firstName; private String lastName; /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @param firstName the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return the lastName */ public String getLastName() { return lastName; } /** * @param lastName the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } }
Serialization.java
package com.codetalk.serialization; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class Serialization { public static void main(String[] args) { Data data = new Data(); String file = "/home/rakesh/data.txt"; data.setFirstName("Rakesh KR"); data.setLastName("KR"); try { FileOutputStream fileOut = new FileOutputStream(file); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(data); out.close(); fileOut.close(); System.out.println("Serialized data is saved in : "+file); } catch(IOException i) { i.printStackTrace(); } catch(Exception e){ e.printStackTrace(); } finally{ data = null; } } }
DeSerialization.java
package com.codetalk.serialization; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class Deserialization { public static void main(String[] args) { Data data = null; String file = "/home/rakesh/data.txt"; try { FileInputStream fileIn = new FileInputStream(file); ObjectInputStream in = new ObjectInputStream(fileIn); data = (Data) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Data class not found"); c.printStackTrace(); } System.out.println("Deserializing Object..."); System.out.println("First Name : "+data.getFirstName()); System.out.println("Last Name : "+data.getLastName()); } }
Output :
Deserializing Object... First Name : Rakesh KR Last Name : KR
Comments
Post a Comment