Last active
August 29, 2015 14:04
-
-
Save kenorb/f208fa36135180417f79 to your computer and use it in GitHub Desktop.
Serialization Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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