xml文件存储和读取数据操作

package org.jboss.seam.example.hibernate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

 

public class XMLFile {
 
 
 public final static String ROOTNAME = "Data";
 
 
 public final static String RECORDROOTNAME = "Record";
 
 
 public final static String FIRSTPAYDATE = "logTime";

 
 public void saveHistoricalRecords(
   List<Company> historicalRecords, String filePathName)
   throws DOMException, IllegalArgumentException,
   IllegalAccessException {

  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
    .newInstance();
  DocumentBuilder docBuilder;
  Document doc = null;
  try {
   docBuilder = docBuilderFactory.newDocumentBuilder();
   File file = new File(filePathName);
   doc = docBuilder.parse(file);
   doc.normalize();
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  fillDocment(historicalRecords, doc);
  writeXML(filePathName, doc);
 }

 
 private void fillDocment(List<Company> records, Document doc)
   throws DOMException, IllegalArgumentException,
   IllegalAccessException {
  for (int i = 0; i < records.size(); i++) {
   Company record = records.get(i);
   // 总根节点的获得
   Element root = (Element) doc.getElementsByTagName_r(
     ROOTNAME).item(0);
   // 记录根节点的建立
   Element element = doc
     .createElement_x(RECORDROOTNAME);
   root.appendChild(element);

   // 添加时间属性
   element.setAttribute(FIRSTPAYDATE, record
     .getDate());

   Field[] recordFileds = record.getClass().getDeclaredFields();

   for (int j = 0; j < recordFileds.length; j++) {
    Field field = recordFileds[j];
    field.setAccessible(true);
    Element attribute = doc.createElement_x(field.getName());
    attribute.setTextContent(String.valueOf(field.get(record)));
    element.appendChild(attribute);
   }
  }
 }

 
 private void writeXML(String filePathName, Document doc) {

  try {
   // 得到转换器工厂类的实例
   TransformerFactory tff = TransformerFactory.newInstance();
   // 创建一个新的转换器,用于执行恒等转换,
   // 即直接将DOM输入源的内容复制到结果文档中。
   Transformer tf = tff.newTransformer();

   // 编码
   tf.setOutputProperty(OutputKeys.ENCODING, "utf-8");
   // 设置转换中实际的输出属性
   tf.setOutputProperty(OutputKeys.INDENT, "yes");

   // 利用文档节点创建一个DOM输入源
   DOMSource ds = new DOMSource(doc);

   PrintWriter pw = new PrintWriter(new FileOutputStream(filePathName));

   // 构造一个StreamResult对象,用于保存转换后结果
   StreamResult sr = new StreamResult(pw);
   // 执行转换
   tf.transform(ds, sr);
  } catch (DOMException e) {
   e.printStackTrace();
  } catch (TransformerFactoryConfigurationError e) {
   e.printStackTrace();
  } catch (TransformerConfigurationException e) {
   e.printStackTrace();
  } catch (TransformerException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }

  
 public boolean createDir(String dir, boolean ignoreIfExitst)
   throws IOException {
  File file = new File(dir);

  if (ignoreIfExitst && file.exists()) {
   return true;
  }

  if (file.mkdir() == true)
   return true;

  else
   return false;
 }

 
 public String getHistoricalStatisticsPath() {
  StringBuffer path = new StringBuffer();

  // 拼接基础路径
  path.append(Company.class.getResource("/").getPath().toString())
    .append("../../../");

  // 拼接statistics
  path.append("statistics").append("/");

  try {
   createDir(path.toString(), true);
  } catch (IOException e) {
   e.printStackTrace();
  }

  return path.toString();
 }

 
 public List<Company> loadAllHistoricalStatistics(
   Company recordType, String filePathName)
   throws InstantiationException, IllegalAccessException {

  List<Company> records = new ArrayList<Company>();
  NodeList nodeList = XMLManager.getNodeListFromXML(filePathName,
    RECORDROOTNAME);
  if (null == nodeList) {
   return new ArrayList<Company>();
  }

  for (int i = 0; i < nodeList.getLength(); i++) {
   Company record = recordType.getClass().newInstance();
   fillFields(nodeList.item(i), record);
   records.add(record);
  }
  return records;
 }
 
 
 private void fillFields(Node node, Company record)
   throws IllegalArgumentException, IllegalAccessException {
  // 统计日期
  record.setDate(node.getAttributes().getNamedItem(
    FIRSTPAYDATE).getNodeValue());
  Element element = (Element) node;

  Field[] recordFields = record.getClass().getDeclaredFields();
  for (int i = 0; i < recordFields.length; i++) {
   Field field = recordFields[i];
   field.setAccessible(true);
   String fieldName = field.getName();
   String value = element.getElementsByTagName_r(fieldName).item(0)
     .getTextContent();
   field.set(record, value);
  }
 }
}

 

package org.jboss.seam.example.hibernate;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;


public class XMLManager {

 
 public static NodeList getNodeListFromXML(String fullPath, String recordName)
 {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  Document doc = null;
  DocumentBuilder db;

  try
  {
   File f = new File(fullPath);
   db = dbf.newDocumentBuilder();
   doc = db.parse(f);
   // 列表查看XML元素
   NodeList nl = doc.getElementsByTagName_r(recordName);
   return nl;
  }
  catch (Exception e)
  {
   try
   {
    StringBuffer contents = new StringBuffer();
    contents.append('<').append("root").append('>').append("</").append("root").append('>');
    writeFileWithoutPath(fullPath, contents);
   }
   catch (DOMException ex)
   {
    ex.printStackTrace();
   }
   catch (TransformerFactoryConfigurationError ex)
   {
    ex.printStackTrace();
   }
  }
  return null;
 }
 
 
 private static void writeFileWithoutPath(String fileName, StringBuffer xhtmlBuffer)
 {
  File file = getFile(fileName);
  BufferedWriter writeFile = null;
  try
  {
   System.out.println("xml file path:"+fileName);
   file.delete();
   file.createNewFile();
   writeFile = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream(file), "UTF8"));
   writeFile.write(xhtmlBuffer.toString());
  
  }
  catch (Exception e)
  {
   //当写文件出现异常删除该文件
   if(file!=null && file.exists())
   {
    file.delete();
   }
   e.printStackTrace();
  }
  finally
  {
   try
   {
      writeFile.close();
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
  }
 }
 
 
    private static File getFile(String path)
    {
     File file = new File(path);
     return file;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值