To implement a very basic example of Serialization in java, lets create Person.java that implements Serializable interface.
Person.java
SerializationMain.java
Person.java
package com.serialization;
import java.io.Serializable;
public class Person implements Serializable {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
SerializationMain.java
package com.serialization;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializationMain {
public static void main(String[] args) throws IOException {
Person person = new Person("Kumar", "Bhatia");
System.out.println("person " + person);
FileOutputStream fos = new FileOutputStream("serial.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.flush();
oos.close();
}
}
If "implements Serializable" is removed from Person.java, following exception occurs:Exception in thread "main" java.io.NotSerializableException: com.serialization.Person
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
at com.serialization.SerializationMain.main(SerializationMain.java:15)
DeSerializationMain.java package com.serialization;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeSerializationMain {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("serial.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Person person = (Person) ois.readObject();
ois.close();
System.out.println("person " + person.getFirstName());
}
}
Run DeSerializationMain.java and the output would be same person object that gets serialized.
No comments:
Post a Comment