实体bean和xml转换

实体bean和xml转换

package com.util;

import com.thoughtworks.xstream.XStream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * 实体bean和xml转换
 * XStream 不关心序列化/逆序列化的类的字段的可见性。
 * 序列化/逆序列化类的字段不需要 getter 和 setter 方法。
 * 序列化/逆序列化的类不需要有默认构造函数。
 * Created by zyb on 2017/5/8.
 */
public class BeanXmlConvert {

    /**
     * object类型转换为xml类型
     *
     * @param obj 待转换的对象
     * @return xml字符串
     */
    public static String printXML(Object obj) {
        XStream xStream = new XStream();
        return xStream.toXML(obj);
    }

    /**
     * xml类型转换为object类型
     *
     * @param xml xml字符串
     * @return Object
     */
    @SuppressWarnings({ "WeakerAccess", "Annotation" })
    public static Object printObj(String xml) {
        XStream xStream = new XStream();
        return xStream.fromXML(xml);
    }

    /**
     * 将object类型转换为xml类型,并写入XML文件(其他格式也可以,比如txt文件)
     *
     * @param obj     对象
     * @param xmlPath 存储文件
     */
    public static void writerXML(Object obj, String xmlPath) {
        try {
            FileOutputStream fs = new FileOutputStream(xmlPath);
            new XStream().toXML(obj, fs);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取XML文件,加载进相应Object类型
     *
     * @param xmlPath 要解析的xml
     * @return 解析后的对象
     */
    public static Object readerXML(String xmlPath) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(xmlPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return new XStream().fromXML(fis);
    }

    @SuppressWarnings({ "MethodCanBeVariableArityMethod", "Annotation" })
    public static void main(String[] args) {
        //UserBean user = new UserBean();
        //user.setId("1");
        //user.setUserName("张三");
        //user.setLoginName("zhangsan");
        //user.setSortID(Integer.valueOf(123));
        //System.out.println(printXML(user));
        //String xml = "<com.mvc.user.bean.UserBean><id>1</id><loginName>zhangsan</loginName><userName>张三</userName><sortID>123</sortID></com.mvc.user.bean.UserBean>";
        //System.out.println(printObj(xml));
        //writerXML(user,"/Users/ZYB/Downloads/user.xml");
        //System.out.println(readerXML("/Users/ZYB/Downloads/user.xml"));
    }
}

 上一篇
定时任务的几种实现 定时任务的几种实现
定时任务的几种实现一.分类从实现的技术上来分类,目前主要有三种技术(或者说有三种产品):Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度
2019-08-19
下一篇 
实体bean导出为excel 实体bean导出为excel
实体bean导出为excelpackage com.util; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.*; im
2019-08-19
  目录