注:原创作品,分享以供交流学习,转载请注明出处。
基本概念:
序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是反序列化,它将流转换为对象。这两个过程
结合起来,可以轻松地存储和传输数据。
实例一:读写文件中的对象
被读写的对象的类
class="java">import java.io.Serializable;
@SuppressWarnings("serial")
public class Person implements Serializable
{
private String name;
private int age;
public Person()
{
}
public Person(String str, int n)
{
System.out.println("Inside Person's Constructor");
name = str;
age = n;
}
String getName()
{
return name;
}
int getAge()
{
return age;
}
}
读写类:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeToFlatFile
{
public static void main(String[] args)
{
SerializeToFlatFile ser = new SerializeToFlatFile();
ser.savePerson();
ser.restorePerson();
}
public void savePerson()
{
Person myPerson = new Person("Jay", 24);
try
{
FileOutputStream fos = new FileOutputStream(
"E:\\workspace\\2010_03\\src\\myPerson.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("Person--Jay,24---Written");
System.out.println("Name is: " + myPerson.getName());
System.out.println("Age is: " + myPerson.getAge());
oos.writeObject(myPerson);
oos.flush();
oos.close();
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
public void restorePerson()
{
try
{
FileInputStream fis = new FileInputStream(
"E:\\workspace\\2010_03\\src\\myPerson.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Person myPerson = (Person) ois.readObject();
System.out.println("\n--------------------\n");
System.out.println("Person--Jay,24---Restored");
System.out.println("Name is: " + myPerson.getName());
System.out.println("Age is: " + myPerson.getAge());
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
}