Skip to content

Instantly share code, notes, and snippets.

@kenorb
Last active August 29, 2015 14:04
Show Gist options
  • Save kenorb/f208fa36135180417f79 to your computer and use it in GitHub Desktop.
Save kenorb/f208fa36135180417f79 to your computer and use it in GitHub Desktop.
Serialization Demo
/*
* Serialization Demo
*
* Serialization is a process of writing a state of an object to a ByteString.
* Deserialization is a process of reading state of an object from a file.
*
* Notes:
* - Only objects of class which implements the serializable interface can be serialized.
*
* Usage:
* javac SerializationDemo.java
* java SerializationDemo
* java DeSerializationDemo
*/
import java.io.*;
class Employee implements Serializable {
private int id;
private String name;
private String role;
public Employee() {
id = 100;
name = "Krish";
role = "Trainer";
}
public void display() {
System.out.println(id+ " " + name + " " + role);
}
}
class SerializationDemo {
public static void main(String[] args) throws Exception {
Employee e1 = new Employee();
System.out.println("Before Serialization:");
e1.display();
FileOutputStream fos = new
FileOutputStream("NewObject.dat");
ObjectOutputStream oos = new
ObjectOutputStream(fos);
oos.writeObject(e1);
System.out.println("Object has been serialized.");
}
}
class DeSerializationDemo {
public static void main(String[] args) throws Exception {
FileInputStream fis = new
FileInputStream("NewObject.dat");
ObjectInputStream ois = new
ObjectInputStream(fis);
Employee e1 = (Employee) ois.readObject(); // Reads the object.
System.out.println("After DeSerialization:");
e1.display();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment