In our example we have got class Person which is implementing Serializable interface. It is needed for serialization our Person class.
In line #42 we are starting serialization and writing serialized data to the file.
In line #64 we are starting reading data from file and then data is deserialized.
It is very simple.
package p_2013_04_03;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
class Person implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private String name;
private int 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 class MySerialization
{
public static void main(String[] args)
{
Person john = new Person();
john.setName("John");
john.setAge(30);
// serialize and write serialized data to the file
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
fos = new FileOutputStream("person.txt");
oos = new ObjectOutputStream(fos);
oos.writeObject(john);
fos.close();
oos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
// Read serialized data from the file and deserialize
FileInputStream fis = null;
ObjectInputStream ois = null;
Person desPersonJohn = new Person();
try
{
fis = new FileInputStream("person.txt");
ois = new ObjectInputStream(fis);
desPersonJohn = (Person)ois.readObject();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
System.out.println(desPersonJohn.getName() + " " + desPersonJohn.getAge());
}
}
No comments:
Post a Comment