Monday 14 April 2014

Java Serialization Example

A simple example of serialization concept in java having logging concept so that you can track object before and after serialization.


Class1 : Person.java

import java.io.Serializable;

public class Person implements Serializable
{
private static final long serialVersionUID = 1L;
String name;
int age;

Person(String name, int age)
{
this.name = name;
this.age=  age;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

public String toString()
{
return name + " " +age;
}
}

Class 2: First.java (Serialization part )

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class First {

private static final Logger logger = Logger.getLogger(First.class.getName());
public static void main(String[] args)
{
SimpleFormatter simpleFormatter = new SimpleFormatter();
Person p =new Person("shubham", 24);
try
{
FileHandler log = new FileHandler("D:\\My\\java\\try\\src\\serialization\\log.txt", true);
log.setFormatter(simpleFormatter);
logger.addHandler(log);
logger.info("Object to be serialize   " + p.toString());
FileOutputStream fileOutputStream = new FileOutputStream("D:\\My\\java\\try\\src\\serialization\\abc.ser");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(p);
objectOutputStream.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}


Class 3: Second.java (Deserialization )

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Second {

private static final Logger logger = Logger.getLogger(Second.class.getName());
static SimpleFormatter simpleFormatter = new SimpleFormatter();

public static void main(String[] args)
{
try
{
FileHandler log = new FileHandler("D:\\My\\java\\try\\src\\serialization\\log.txt", true);
log.setFormatter(simpleFormatter);
logger.addHandler(log);

FileInputStream fileInputStream = new FileInputStream("abc.ser");
ObjectInputStream objectOutputStream = new ObjectInputStream(fileInputStream);
Person p = (Person) objectOutputStream.readObject();
objectOutputStream.close();
logger.info("Object deserialized is "+p.toString());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}

No comments:

Post a Comment