对象与xml互转

package test;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

public class Object2XML {
	/**
	 * 对象输到XML文件
	 * 
	 * @param obj
	 *            待输出的对象
	 * @param outFileName
	 *            目标XML文件的文件名
	 * @return 返回输出XML文件的路径
	 * @throws FileNotFoundException
	 * @throws UnsupportedEncodingException 
	 */

	public static String object2XML(Object obj, String outFileName) throws FileNotFoundException, UnsupportedEncodingException {
		// 构造输出XML文件的字节输出流
		File outFile = new File(outFileName);
//		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile));
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		XMLEncoder xmlEncoder = new XMLEncoder(bos);// 构造一个XML编辑器
		xmlEncoder.writeObject(obj);// 使用XML编码器写对象
		xmlEncoder.close();// 关闭编码器
		return new String(bos.toByteArray(),"utf-8");
	}

	/**
	 * 把XML文件解码成对象
	 * 
	 * @param inFileName输入的XML文件
	 * @return 返回生成的对象
	 * @throws FileNotFoundException
	 */
	public static Object xml2Object(String inFileName) throws FileNotFoundException {
		// 构造输入的XML文件的字节输入流
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inFileName));
		XMLDecoder xmlDecoder = new XMLDecoder(bis);// 构造一个XML解码器
		Object obj = xmlDecoder.readObject();// 使用XML解码器读对象
		xmlDecoder.close();// 关闭解码器
		return obj;
	}

	public static void main(String[] args) throws Exception {
		// 构造一个StudentBean对象
//		StudentBean student = new StudentBean();
//		student.setName("wangwu");
//		student.setGender("male");
//		student.setAge(15);
//		student.setPhone("55556666");
//
//		// 将StudentBean对象写到XML文件
//		String fileName = "AStudent.xml";
//		String s = Object2XML.object2XML(student, fileName);
//		
//		System.out.println(s);
//		// 从XML文件读StudentBean对象
//		StudentBean aStudent = (StudentBean) Object2XML.xml2Object(fileName);
//		System.out.println(aStudent.toString());
		BenefitDataResponse response = new BenefitDataResponse();
		response.setCode("111111111111111111111111111111111");
		response.setName("我我我我我我我我我我我我我我我我我我");
		String s = "afasfd@af2asfd@afas3fd@afa4sfd@afa4sfd@afa5sfd";
		response.setVal(s.split("@"));
		String fileName = "AStudent.xml";
		String ss = Object2XML.object2XML(response, fileName);
		System.out.println(ss);
	}

	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值