Java对象与XML文档的互相转换(Object/XML)

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class Object2XML {


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

return outFile.getAbsolutePath();
}


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

return obj;
}

public static void main(String[] args) throws IOException {

// 构造一个StudentBean对象
StudentBean student = new StudentBean();
student.setName("wamgwu");
student.setGender("male");
student.setAge(15);
student.setPhone("55556666");

// 将StudentBean对象写到XML文件
String fileName = "AStudent.xml";
Object2XML.object2XML(student, fileName);
// 从XML文件读StudentBean对象
StudentBean aStudent = (StudentBean)Object2XML.xml2Object(fileName);
// 输出读到的对象
System.out.println(aStudent.toString());
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值