java序列化

阅读更多

Java序列化与反序列化(实践)

基本概念:
序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,可以轻松地存储和传输数据。

昨天在一本书上看到了,好好实践了一下,序列化为一般文件,也序列化为XML文件(使用XStream)。

用于序列化的实体类Person.java    代码如下(记得需要实现Serializable接口):

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();
        }
    }
}
 


序列化、反序列化为一般的文件,SerializeToFlatFile.java类的代码如下:运行结果为(console输出),当然可以查看到myPerson.txt文件已经生成:

Inside Person's Constructor
Person--Jay,24---Written
Name is: Jay
Age is: 24

--------------------

Person--Jay,24---Restored
Name is: Jay
Age is: 24

http://www.cnblogs.com/bluesky5304/archive/2010/04/07/1706061.html

你可能感兴趣的:(java序列化)