对象与XML之间的转换

来源:互联网 发布:java waite() 编辑:程序博客网 时间:2024/04/30 21:51
 

package book.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;

 

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

 public static String object2XML(Object obj,String outFileName)throws FileNotFoundException{
  //构造输出XML文件的字节输出流
  File outFile=new File(outFileName);
  BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(outFile));
  XMLEncoder xmlEncoder=new XMLEncoder(bos);//构造一个XML编辑器
  xmlEncoder.writeObject(obj);//使用XML编码器写对象
  xmlEncoder.close();//关闭编码器
  return outFile.getAbsolutePath();
 }
 /**
  * 把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 FileNotFoundException {
  //构造一个StudentBean对象
  StudentBean student=new StudentBean();
  student.setName("wangwu");
  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());
 }
}

原创粉丝点击