一个使用JAVA xmlencoder 例子

发布时间:2023-06-30 16:35:34

XMLENCODER可以以XML的形式存储JAVA对象,当需要再次使用时,可以使用XMLDECODER进行恢复,比JAVA对象流更容易使用.

测试程序:

package com.sitechasia.test.beans;  import java.io.OutputStream;  import junit.framework.TestCase;  import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;  import com.funambol.framework.engine.source.ContentType; import com.funambol.framework.engine.source.SyncSourceInfo; import com.sitechasia.test.tools.BeanXmlEncoder; import com.sitechasia.uab.sync.source.UabSyncSource;  public class TestBeanXmlEncoder extends TestCase {   public TestBeanXmlEncoder(String arg0) {   super(arg0);  }   protected void setUp() throws Exception {   super.setUp();  }   Log log = LogFactory.getLog(TestBeanXmlEncoder.class);   public void testEncodeUabSyncSource() {   OutputStream beanout = System.out;   UabSyncSource us = null;   try {    us = new UabSyncSource();    us.setDebug(true);    us.setName(card3);    us.setSourceURI(card3);     SyncSourceInfo info = null;    ContentType[] cts = new ContentType[3];    cts[0] = new ContentType("text/vcard", "2.1");    cts[1] = new ContentType("text/x-vcard", "2.1");    cts[2] = new ContentType("text/plain", "2.1");    info = new SyncSourceInfo(cts, 1);    us.setInfo(info);     BeanXmlEncoder.EncoderBean(us, beanout);    } catch (Exception e) {    System.out.println("Fail to sav Bean");   }  }      protected void tearDown() throws Exception {   super.tearDown();  }  }

工具类 :

package com.sitechasia.test.tools;  import java.beans.XMLEncoder; import java.io.OutputStream;  import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;  /**  * 编码并保存JAVA类  * @author  MCSA   *  */ public class BeanXmlEncoder {  final static Log log = LogFactory.getLog(BeanXmlEncoder.class);  public static void EncoderBean(Object bean, OutputStream beanstore) {   XMLEncoder encoder = null;   try {    encoder = new XMLEncoder(beanstore);    encoder.writeObject(bean);    encoder.flush();    encoder.close();   } catch (Exception e) {    log.error("Fail Encode bean"+ToStringBuilder.reflectionToString(bean));    log.error("--------------------------------------------------------- ");    log.error(ExceptionUtils.getStackTrace(e));   }   }  }

上一篇 用JUnit框架实现Java单元测试
下一篇 java解析Excel使用hutool工具类

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题