Java Object 序列化成XML以及XML反序列化成Java Object

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
package org.sl.bean;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

public class ObjectXmlSerial {
   
    public static void main(String[] args) throws IOException{
        UserBean user = new UserBean();
        OtherUserInfoBean otherUserInfo = new OtherUserInfoBean();
       
        otherUserInfo.setAddress("汉字");
        otherUserInfo.setEmail("test@test.com");
       
        user.setName("hello");
        user.setPassword("world");
       
        user.setOtherUserInfo(otherUserInfo);
                         
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        BufferedOutputStream bufferOut = new BufferedOutputStream(byteArrayOut);
       
        writeObjectToXML(bufferOut, user);
        byte[] bys = byteArrayOut.toByteArray();
       
        byteArrayOut.close();
        bufferOut.close();
       
       
        ByteArrayInputStream byteArrayIn = new ByteArrayInputStream(bys);
        BufferedInputStream bufferIn = new BufferedInputStream(byteArrayIn);
       
        UserBean user1 = readObjectFromXML(bufferIn);
       
        byteArrayIn.close();
        bufferIn.close();       
       
        System.out.println(user1.getName());
        System.out.println(user1.getOtherUserInfo().getAddress());
    }
   
    public static <T extends Serializable> void writeObjectToXML(OutputStream out, T obj){
        XMLEncoder xmlEncoder = null;
       
        try{
            xmlEncoder = new XMLEncoder(out);
            xmlEncoder.writeObject(obj);
        }finally{
            if(null != xmlEncoder)
                xmlEncoder.close();
        }
    }
   
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T readObjectFromXML(InputStream in){
        T obj = null;
        XMLDecoder xmlDecoder = null;
       
        try{
            xmlDecoder = new XMLDecoder(in);
            obj = (T) xmlDecoder.readObject();
        }finally{
            if(null != xmlDecoder)
                xmlDecoder.close();
        }
        return obj;
    }
}


Kyle Wang

posted on 2011-07-04 20:55 王树东 阅读(1698) 评论(0)  编辑  收藏 所属分类: Java Skills Learning and SharingCode Templates


只有注册用户登录后才能发表评论。


网站导航:
 
<2011年7月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

公告

常用链接

留言簿

随笔分类(17)

随笔档案(15)

文章分类(4)

文章档案(5)

收藏夹(4)

Algorithm

Design

Environment Setup

Installer

Maven

MINA

OS

Skills for Java

VIM

搜索

最新评论

阅读排行榜

评论排行榜