基于服务器XMLCRUD操作工具类

来源:互联网 发布:网络电视不清晰怎么办 编辑:程序博客网 时间:2024/05/17 05:54

考虑减少不必要业务对数据库的影响,将不重要的通告展示交由xml存储,这就有了XMLUtil工具类:

注意写入xml路径问题,单个java文件路径会在src下,这里指定文件路径在tomcat下;然后这个util针对Notice实体开发,可自行修改。

<pre name="code" class="java">package com.dayang.audit.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List; import net.sf.json.JSONArray;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter; public class XMLUtil {    private static String fileURL="notice.xml";    /**     * 获取XML中所有的通告信息     * @return     */    public static List<Notice> getAllNotice(){        Document document=getDocument();        Element rootElement=document.getRootElement();                 List<Element> noticeElements=rootElement.elements();        List<Notice> notices=new ArrayList<Notice>();        for (Element noticeElement : noticeElements) {            Notice notice=new Notice();            notice.setId(noticeElement.attributeValue("id"));            notice.setTitle(noticeElement.element("title").getTextTrim());            notice.setPriority(noticeElement.element("priority").getTextTrim());            notice.setContent(noticeElement.element("content").getTextTrim());            notice.setStarttime(noticeElement.element("starttime").getTextTrim());            notice.setEndtime(noticeElement.element("endtime").getTextTrim());            notices.add(notice);        }        return notices;    }        /**     * 条件获取XML中所有的通告信息     * @return     */    public static List<Notice> selectNoticeByTime(String time){        Document document=getDocument();        Element rootElement=document.getRootElement();                 List<Element> noticeElements=rootElement.elements();        List<Notice> notices=new ArrayList<Notice>();        for (Element noticeElement : noticeElements) {        System.out.println(noticeElement.element("starttime").getTextTrim());        if(noticeElement.element("starttime").getTextTrim().compareTo(time) <= 0         && noticeElement.element("endtime").getTextTrim().compareTo(time) >= 0){                Notice notice=new Notice();                notice.setId(noticeElement.attributeValue("id"));                notice.setTitle(noticeElement.element("title").getTextTrim());                notice.setPriority(noticeElement.element("priority").getTextTrim());                notice.setContent(noticeElement.element("content").getTextTrim());                notice.setStarttime(noticeElement.element("starttime").getTextTrim());                notice.setEndtime(noticeElement.element("endtime").getTextTrim());                notices.add(notice);            }        }        return notices;    }        /**     * 获取某一个Id的信息     * @return     */    public static Notice findById(String id){        Document document=getDocument();        Element rootElement=document.getRootElement();                 List<Element> noticeElements=rootElement.elements();        Notice notice=new Notice();        for (Element noticeElement : noticeElements) {         if(noticeElement.attributeValue("id").equals(id)){                notice.setId(noticeElement.attributeValue("id"));                notice.setTitle(noticeElement.element("title").getTextTrim());                notice.setPriority(noticeElement.element("priority").getTextTrim());                notice.setContent(noticeElement.element("content").getTextTrim());                notice.setStarttime(noticeElement.element("starttime").getTextTrim());                notice.setEndtime(noticeElement.element("endtime").getTextTrim());                return notice;            }        }        return notice;    }        /**     * 向XML文件中添加一个notice(不允许为空)     * @param notice     */    public static void add(Notice notice){        Document document=getDocument();        Element rootElement=document.getRootElement();                 Element noticeElement=rootElement.addElement("notice");        noticeElement.addAttribute("id",getMaxId()+1+"");        Element titleElement=noticeElement.addElement("title");        Element priorityElement=noticeElement.addElement("priority");        Element contentElement=noticeElement.addElement("content");        Element starttimeElement=noticeElement.addElement("starttime");        Element endtimeElement=noticeElement.addElement("endtime");        titleElement.setText(notice.getTitle());        priorityElement.setText(notice.getPriority());        contentElement.setText(notice.getContent());        starttimeElement.setText(notice.getStarttime());        endtimeElement.setText(notice.getEndtime());                 write2XML(document);    }    /**     * 根据id删除notice     * @param id     */    public static void deleteById(String id){        Document document=getDocument();        Element rootElement=document.getRootElement();                 List<Element> noticeElements=rootElement.elements("notice");        for (Element noticeElement : noticeElements) {            if(noticeElement.attributeValue("id").equals(id)){                System.out.println("开始删除.....");                rootElement.remove(noticeElement);                System.out.println("删除结束.....");            }        }        write2XML(document);    }    /**     * 修改notice信息     * @param notice     */    public static void update(Notice notice){        Document document=getDocument();        Element rootElement=document.getRootElement();                 List<Element> noticeElements=rootElement.elements();        for (Element noticeElement : noticeElements) {            if(noticeElement.attributeValue("id").equals(notice.getId())){                List<Element> elements=noticeElement.elements();                noticeElement.element("title").setText(notice.getTitle());                noticeElement.element("priority").setText(notice.getPriority());                noticeElement.element("content").setText(notice.getContent());                noticeElement.element("starttime").setText(notice.getStarttime());                noticeElement.element("endtime").setText(notice.getEndtime());            }        }        write2XML(document);    }         /**     * 获取根节点     * @return rootElement     */    public static Document getDocument(){        try {            SAXReader saxReader=new SAXReader();//            InputStream in=XMLUtil.class.getResourceAsStream("/notice.xml");//拿取src下文件            String filePath = getProjectPath().substring(1)+fileURL;            File file = new File(filePath);            if(!file.exists()){            String oldPath =getSrcPath()+fileURL;            copyFile(oldPath, filePath);            }            System.out.println(filePath);            InputStream in=new FileInputStream(filePath);            Document document=saxReader.read(in);                         return document;        } catch (Exception e) {            e.printStackTrace();            throw new RuntimeException(e);        }    }    /**     * 把内容写到XML文件中     * @param document     */    public static void write2XML(Document document){        try {            OutputFormat format=new OutputFormat("  ", true, "utf-8");            format.setTrimText(true);            XMLWriter writer = new XMLWriter(format);                        writer.setOutputStream(new FileOutputStream(getProjectPath()+fileURL));//            writer.setOutputStream(new FileOutputStream("src/"+fileURL));            writer.write(document);            writer.close();        } catch (Exception e) {            e.printStackTrace();            throw new RuntimeException(e);        }    }    /**     * 获取xml文件中noticeId的最大值     * @return int     */    public static int getMaxId(){        int maxId=0;        Document document=getDocument();        Element rootElement=document.getRootElement();        List<Element> noticeElements=rootElement.elements();        for (Element element : noticeElements) {            int id=Integer.valueOf(element.attributeValue("id"));            if(maxId<id){                maxId=id;            }        }        return maxId;    }        /** * 得到工程的物理路径(例如:D:/Workspaces/) * @return * @throws Exception */public static String getProjectPath() {String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();        System.out.println(path);        path = path.replace("file:/", "");        path = path.replace("WEB-INF/classes/", "");        path = path.replace("WebContent/", "");        path = path.replace("CCTVCensorAndroid/", "");        path = path.replace("%20", " ");//        path+="\\CCTVCensorAndroid\\WEB-INF\\classes\\";return path;}/** * 得到项目src路径(例如:/D:/lgl/Workspaces/CCTVCensorAndroid/WebContent/WEB-INF/classes/notice.xml) * @return * @throws Exception */public static String getSrcPath() {String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();System.out.println(path);path = path.replace("file:/", "");path = path.replace("%20", " ");return path;}/** * 复制单个文件 *  * @param oldPath *            String 原文件路径 如:c:/fqf.txt * @param newPath *            String 复制后路径 如:f:/fqf.txt * @return boolean */public static void copyFile(String oldPath, String newPath) {try {int bytesum = 0;int byteread = 0;File oldfile = new File(oldPath);if (oldfile.exists()) { // 文件存在时InputStream inStream = new FileInputStream(oldPath); // 读入原文件FileOutputStream fs = new FileOutputStream(newPath);byte[] buffer = new byte[1444];int length;while ((byteread = inStream.read(buffer)) != -1) {bytesum += byteread; // 字节数 文件大小fs.write(buffer, 0, byteread);}inStream.close();}} catch (Exception e) {System.out.println("复制单个文件操作出错");e.printStackTrace();}}    public static void main(String[] args) {//    Notice nd = new Notice();//    nd.setTitle("程序测试2");//    nd.setPriority("低2");//    nd.setContent("低2");//    nd.setStarttime("20160709");//    nd.setEndtime("20160712");//    add(nd);//    Notice ns = new Notice();//    ns.setId("3");//    ns.setTitle("程序测试1");//    ns.setPriority("低1");//    ns.setContent("低1");//    ns.setStarttime("20160709");//    ns.setEndtime("20160712");//    update(ns);//    deleteById("4");List<Notice> notices = getAllNotice();JSONArray fromObject = JSONArray.fromObject(notices);System.out.println(fromObject.toString());for(Notice n : notices){System.out.println(n.toString());}}}
xml文件格式:

<?xml version="1.0" encoding="utf-8"?><notice>  <notice id="1">    <starttime>20160705</starttime>    <endtime>20160708</endtime>    <title>测试</title>    <priority>高</priority>    <content>下发通知单</content>  </notice></notice>
notice实体大纲:

private String id;private String title;private String priority;private String content;private String starttime;private String endtime;


1 0