All things are difficult before they are easy. 没有软件的裸机是一具僵尸,没有硬件的软件是一个幽灵。2012,专注于Linux和C语言,关注自动化、性能测试,关注开源社区和开源测试工具、方法,尝试测试团队管理!

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

上一篇 / 下一篇  2010-03-21 12:54:26 / 个人分类: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;
    }
}


序列化、反序列化为一般的文件,SerializeToFlatFile.java类的代码如下:
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 s = 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 is = 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();
        }
    }
}

运行结果为(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


序列化、 反序列化为XML文件,我使用了XStream来序列化,需要引入xstream-1.3.1.jar包的支持,
http://xstream.codehaus.org/download.html  处可以下载jar,然后引入到Eclipse中的build path中。
Serialize.java的代码如下:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.thoughtworks.xstream.*;

public class Serialize {
    public static void main(String[] args) {
        Serialize ser = new Serialize();
        ser.serializeToXml();
        ser.deSerializeFromXml();
    }
   
public void serializeToXml(){
        Person[] myPerson = new Person[2];
        myPerson[0] = new Person("Jay",24);
        myPerson[1] = new Person("Tom",23);
       
        XStream xstream = new XStream(); 
        try {
            FileOutputStream fos = new FileOutputStream("E:\\workspace\\2010_03\\src\\myPerson.xml");
             xstream.toXML(myPerson,fos);
             } catch (FileNotFoundException ex) {
             ex.printStackTrace();
             }      
        System.out.println(xstream.toXML(myPerson));
    }
    public void deSerializeFromXml(){
         XStream xs = new XStream();
         Person[] myPerson = null;

         try {
         FileInputStream fis = new FileInputStream("E:\\workspace\\2010_03\\src\\myPerson.xml");
         myPerson=(Person[])xs.fromXML(fis);
         if (myPerson != null)
         {
             int len = myPerson.length;
             for (int i=0;i<len;i++)
             {
                 System.out.println(myPerson[i].getName());
                 System.out.println(myPerson[i].getAge());
             }

         }
         } catch (FileNotFoundException ex) {
         ex.printStackTrace();
         }
    }
}

运行结果为(console输出),当 然可以查看到myPerson.xml文件已经生成:
Inside Person's Constructor
Inside Person's Constructor
<Person-array>
  <Person>
    <name>Jay</name>
    <age>24</age>
  </Person>
  <Person>
    <name>Tom</name>
    <age>23</age>
  </Person>
</Person-array>
Jay
24
Tom
23


参考资料:
http://developer.51cto.com/art/200908/147650.htm
http://www.ibm.com/developerworks/cn/xml/x-xstream/#resources
http://www.cnblogs.com/stephencat/archive/2007/06/05/772520.html

TAG: 序列化 java xstream 反序列化

 

评分:0

我来说两句

smile665

smile665

Stay hungry, stay foolish. 得意之时谨记,一半命运还掌握在上帝手里;失意之时须知,一半命运还掌握在自己手里。

日历

« 2024-04-29  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 956192
  • 日志数: 220
  • 建立时间: 2008-11-06
  • 更新时间: 2012-10-06

RSS订阅

Open Toolbar