xml中文件操作功能類的示例分析

小編給大家分享一下xml中文件操作功能類的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

創(chuàng)新互聯(lián)專注于于洪企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站設(shè)計(jì),電子商務(wù)商城網(wǎng)站建設(shè)。于洪網(wǎng)站建設(shè)公司,為于洪等地區(qū)提供建站服務(wù)。全流程按需設(shè)計(jì),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)

FileUtil.xml

package com.novel.util;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
/**
 * @author cy
 *
 * @date 2015年7月24日 上午8:38:38
 *
 * @Description 關(guān)于文件的一些工具
 */
public class FileUtils {
    /**
     * 將文件中所有內(nèi)容讀取到字符串中
     * 
     * @param filePath
     *            文件路徑
     * @return 文件內(nèi)容
     */
    public static String getStringFromFile(String filePath) {
        File file = new File(filePath) ;
        if(!file.exists()){
             return "" ;
        }
        /**
         * 處理文件讀取亂碼問題 :
         * 只要判定兩種常見的編碼就可以了:GBK和UTF-8。由于中文Windows默認(rèn)的編碼是GBK,所以一般只要判定UTF-8編碼格式。
            *對(duì)于UTF-8編碼格式的文本文件,其前3個(gè)字節(jié)的值就是-17、-69、-65
         */
        try{
            byte[] firstThreeByte = new byte[3] ;
            InputStream in = new FileInputStream(file) ;
            in.read(firstThreeByte) ;
            in.close() ;
            String encoding = "" ;
            if(firstThreeByte[0] == -17 && firstThreeByte[1] == -16 && firstThreeByte[2] == -65){
                encoding = "utf-8" ;
            }else{
                encoding = "gbk" ;
            }
             InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);      
            Long filelength = file.length() / 2 ; // 該方法獲取的是文件字節(jié)長度,
                                                  //而我要?jiǎng)?chuàng)建的是char數(shù)組,char占兩個(gè)字節(jié),
                                                  //byte一個(gè)字節(jié),所以除以2表示的是該文件的字符長度
            char[] filecontent = new char[filelength.intValue()] ; 
            read.read(filecontent) ;
            return new String(filecontent) ;
        }catch(Exception e ){
            e.printStackTrace();
            return "" ;
        }
    }
 
    /**
     * 將字符串寫入文件
     * 
     * @param content
     *            字符串內(nèi)容
     * @param filePath
     *            文件路徑
     * @throws IOException
     */
    public static void writeStringToFile(String content, String filePath)
            throws IOException {
 
        File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(file);
        out.write(content.getBytes());
        out.close();
    }
    /**
     * 刪除指定的文件 
     * @param filePath文件路徑 
     */
    public static void deleteFile(String filePath ) {
        File file = new File(filePath) ;
        if(file.exists()){
            file.delete() ;
        }
    }
}

XmlUtil.java

package com.novel.util;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
 
import com.novel.entity.Novel;
import com.novel.entity.User;
 
/**
 * @author cy
 *
 * @date 2015年7月23日 下午3:19:06
 *
 * @Description 關(guān)于xml的操作
 */
public class XmlUtil {
    /**
     * 目標(biāo)xml為 config/users.xml
     * 
     * @param user
     *            將要被寫入xml的User對(duì)象
     * @return 是否成功
     */
    public static boolean writeUserToXml(User user) {
        try {
            Document doc = getDocumentFromXml("config/users.xml");
            Element newUserElement = doc.createElement("user");
            Element newUsernameElement = doc.createElement("name");
            Text nameTextNode = doc.createTextNode("nameValue");
            nameTextNode.setNodeValue(user.getName());
            newUsernameElement.appendChild(nameTextNode);
            Element newUserPwdElement = doc.createElement("pwd");
            Text pwdTextNode = doc.createTextNode("pwdValue");
            pwdTextNode.setNodeValue(user.getName());
            newUserPwdElement.appendChild(pwdTextNode);
            newUserElement.appendChild(newUsernameElement);
            newUserElement.appendChild(newUserPwdElement);
            Element usersElement = (Element) doc.getElementsByTagName("users")
                    .item(0);
            usersElement.appendChild(newUserElement);
 
            writeDocumentToFile(doc, "config/users.xml");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 
     * @param doc
     *            XML中的Document對(duì)象
     * @param filePath
     *            輸出的文件路徑
     * @throws TransformerFactoryConfigurationError
     * @throws TransformerConfigurationException
     * @throws TransformerException
     */
    private static void writeDocumentToFile(Document doc, String filePath)
            throws TransformerFactoryConfigurationError,
            TransformerConfigurationException, TransformerException {
        // 寫入到硬盤
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        /** 編碼 */
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filePath));
        transformer.transform(source, result);
    }
 
    /**
     * 加載config/users.xml中用戶信息到對(duì)象中
     * 
     * @return 加載后的對(duì)象
     */
    public static Map<String, User> initUser() {
        InitUser.users = new HashMap<String, User>();
        try {
            Document doc = getDocumentFromXml("config/users.xml");
            NodeList usersNodeList = doc.getElementsByTagName("user");
            for (int i = 0; i < usersNodeList.getLength(); i++) {
                Element userElement = (Element) usersNodeList.item(i);
                String userName = ((Element) (userElement
                        .getElementsByTagName("name").item(0))).getFirstChild()
                        .getNodeValue();
                String passwd = ((Element) (userElement
                        .getElementsByTagName("pwd").item(0))).getFirstChild()
                        .getNodeValue();
                InitUser.users.put(userName, new User(userName, passwd));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return InitUser.users;
        }
    }
 
    /**
     * 從xml中獲取服務(wù)器運(yùn)行的端口
     * 
     * @return server.xml文件中的端口號(hào)
     */
    public static int getServerPort() {
        try {
            Document doc = getDocumentFromXml("config/server.xml");
            int serverPort = Integer.parseInt(doc
                    .getElementsByTagName("server-port").item(0)
                    .getFirstChild().getNodeValue());
            return serverPort;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /**
     * 
     * @param xmlPath
     *            xml文件的位置
     * @return 這個(gè)xml文件相應(yīng)的Document對(duì)象
     * @throws SAXException
     * @throws IOException
     * @throws ParserConfigurationException
     */
    public static Document getDocumentFromXml(String xmlPath)
            throws SAXException, IOException, ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlPath);
        return doc;
    }
 
    /**
     * 讀取xml中小說的信息到List中
     * 
     * @param novelId
     *            小說id
     * @return 小說列表
     * @throws ParserConfigurationException 
     * @throws IOException 
     * @throws SAXException 
     */
    public static List<Novel> getNovelListFromXml(String filePath) throws SAXException, IOException, ParserConfigurationException {
        List<Novel> novelList = new ArrayList<Novel>();
        Document doc = getDocumentFromXml(filePath);
        NodeList novels = doc.getElementsByTagName("novel");
        for (int i = 0; i < novels.getLength(); i++) {
            Element novel = ((Element) novels.item(i));
            int id = Integer.parseInt(novel.getElementsByTagName("id").item(0)
                    .getFirstChild().getNodeValue());
            String name = novel.getElementsByTagName("name").item(0)
                    .getFirstChild().getNodeValue();
            String author = novel.getElementsByTagName("author").item(0)
                    .getFirstChild().getNodeValue();
            String category = novel.getElementsByTagName("category").item(0)
                    .getFirstChild().getNodeValue();
            String description = novel.getElementsByTagName("description")
                    .item(0).getFirstChild().getNodeValue();
             
            Novel oneNovel = new Novel(id, category, name, author, description);
            novelList.add(oneNovel);
        }
        return novelList ;
    }
    /**
     * 將Novel信息寫入到config/novelsInfo.xml中并且將小說內(nèi)容寫入到novel文件夾下
     * @param novel 小說對(duì)象
     * @return 是否寫入成功 
     * TODO:確定原子操作
     */
    public static boolean writeNovelToFile(Novel novel ) {
        /**
         * 先將小說內(nèi)容寫入到novel文件夾下,再將小說信息寫入到config/novelsInfo.xml中
         */
        try{
            FileUtils.writeStringToFile(novel.getContent(), "novel/" + novel.getName() + ".txt");
            XmlUtil.writeNovelInfoToXml(novel) ;
            return true ;
        }catch(Exception e ){
            /**
             * 如果寫入小說到文件中出現(xiàn)問題,要將已經(jīng)寫入的信息刪除
             * 這段代碼應(yīng)該很少執(zhí)行到 ~~~~
             * 
             */
            System.out.println("小說寫入文件失敗,正在回滾~~");
            FileUtils.deleteFile("novel/" + novel.getName() + ".txt") ;
            XmlUtil.deleteNovelInfoFromXml(novel) ;
            e.printStackTrace();
            return false ;
        }
    }
 
    /**
     * 從config/novelsInfo.xml中刪除與novel對(duì)象相對(duì)應(yīng)的的novel標(biāo)簽,根據(jù)ID號(hào)判斷是否相同
     * 
     * @param novel
     *            小說對(duì)象
     */
    public static void deleteNovelInfoFromXml(Novel novel) {
        try {
            Document doc = getDocumentFromXml("config/novelsInfo.xml");
            Element novelsElement = (Element) doc
                    .getElementsByTagName("novels").item(0);
            NodeList novelElements = novelsElement
                    .getElementsByTagName("novel");
 
            Node deleteElement = null;
            for (int i = 0; i < novelElements.getLength(); i++) {
                String id = ((Element) novelElements.item(i))
                        .getElementsByTagName("id").item(0).getFirstChild()
                        .getNodeValue();
                if (id.equals(String.valueOf(novel.getId()))) {
                    deleteElement = novelElements.item(i);
                    break;
                }
            }
            novelsElement.removeChild(deleteElement);
            writeDocumentToFile(doc, "config/novlesInfo.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 將小說信息寫入到config/novelsInfo.xml文件中
     * @param novel小說對(duì)象
     */
    public static void writeNovelInfoToXml(Novel novel){
        Document doc = null ;
        try {
            doc = getDocumentFromXml("config/novelsInfo.xml");
        } catch (Exception e) {
            e.printStackTrace();
            return ;
        }
        Element novelDocument = (Element)doc.createElement("novel") ;
        // id
        Element novelIdDocument = (Element)doc.createElement("id") ;
        Text novelIdTextNode = doc.createTextNode("idValue") ;
        novelIdTextNode.setNodeValue(String.valueOf(novel.getId()));
        novelIdDocument.appendChild(novelIdTextNode);
        // name
        Element novelNameDocument = (Element)doc.createElement("name") ;
        Text novelNameTextNode = doc.createTextNode("nameValue") ;
        novelNameTextNode.setNodeValue(String.valueOf(novel.getName()));
        novelNameDocument.appendChild(novelNameTextNode);
        // author
        Element novelAuthorDocument = (Element)doc.createElement("author") ;
        Text novelAuthorTextNode = doc.createTextNode("authorValue") ;
        novelAuthorTextNode.setNodeValue(String.valueOf(novel.getAuthor()));
        novelAuthorDocument.appendChild(novelAuthorTextNode);
        // category
        Element novelCategoryDocument = (Element)doc.createElement("category") ;
        Text novelCategoryTextNode = doc.createTextNode("categoryValue") ;
        novelCategoryTextNode.setNodeValue(String.valueOf(novel.getCategory()));
        novelCategoryDocument.appendChild(novelCategoryTextNode);
        // description 
        Element novelDescriptionDocument = (Element)doc.createElement("description") ;
        Text novelDescriptionTextNode = doc.createTextNode("descriptionValue") ;
        novelDescriptionTextNode.setNodeValue(String.valueOf(novel.getDescription()));
        novelDescriptionDocument.appendChild(novelDescriptionTextNode);
         
        novelDocument.appendChild(novelIdDocument) ;
        novelDocument.appendChild(novelNameDocument) ;
        novelDocument.appendChild(novelAuthorDocument) ;
        novelDocument.appendChild(novelCategoryDocument) ;
        novelDocument.appendChild(novelDescriptionDocument) ;
        doc.getElementsByTagName("novels").item(0).appendChild(novelDocument) ;
        // 寫到文件中
        try {
            writeDocumentToFile(doc, "config/novelsInfo.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

以上是“xml中文件操作功能類的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

標(biāo)題名稱:xml中文件操作功能類的示例分析
路徑分享:http://muchs.cn/article42/ihdohc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站、全網(wǎng)營銷推廣網(wǎng)站建設(shè)、Google微信公眾號(hào)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營