搜尋
首頁後端開發XML/RSS教程xml,檔案操作功能類別的範例程式碼詳解

我一個專案中用到的,裡面的方法不是太通用,但是可以從裡面找到一些有用的程式碼,以後慢慢添補更新:

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 关于文件的一些工具
 */
public class FileUtils {
    /**
     * 将文件中所有内容读取到字符串中
     * 
     * @param filePath
     *            文件路径
     * @return 文件内容
     */
    public static String getStringFromFile(String filePath) {
        File file = new File(filePath) ;
        if(!file.exists()){
             return "" ;
        }
        /**
         * 处理文件读取乱码问题 :
         * 只要判定两种常见的编码就可以了:GBK和UTF-8。由于中文Windows默认的编码是GBK,所以一般只要判定UTF-8编码格式。
            *对于UTF-8编码格式的文本文件,其前3个字节的值就是-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 ; // 该方法获取的是文件字节长度,
                                                  //而我要创建的是char数组,char占两个字节,
                                                  //byte一个字节,所以除以2表示的是该文件的字符长度
            char[] filecontent = new char[filelength.intValue()] ; 
            read.read(filecontent) ;
            return new String(filecontent) ;
        }catch(Exception e ){
            e.printStackTrace();
            return "" ;
        }
    }
 
    /**
     * 将字符串写入文件
     * 
     * @param content
     *            字符串内容
     * @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 关于xml的操作
 */
public class XmlUtil {
    /**
     * 目标xml为 config/users.xml
     * 
     * @param user
     *            将要被写入xml的User对象
     * @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对象
     * @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中用户信息到对象中
     * 
     * @return 加载后的对象
     */
    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中获取服务器运行的端口
     * 
     * @return server.xml文件中的端口号
     */
    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 这个xml文件相应的Document对象
     * @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中并且将小说内容写入到novel文件夹下
     * @param novel 小说对象
     * @return 是否写入成功 
     * TODO:确定原子操作
     */
    public static boolean writeNovelToFile(Novel novel ) {
        /**
         * 先将小说内容写入到novel文件夹下,再将小说信息写入到config/novelsInfo.xml中
         */
        try{
            FileUtils.writeStringToFile(novel.getContent(), "novel/" + novel.getName() + ".txt");
            XmlUtil.writeNovelInfoToXml(novel) ;
            return true ;
        }catch(Exception e ){
            /**
             * 如果写入小说到文件中出现问题,要将已经写入的信息删除
             * 这段代码应该很少执行到 ~~~~
             * 
             */
            System.out.println("小说写入文件失败,正在回滚~~");
            FileUtils.deleteFile("novel/" + novel.getName() + ".txt") ;
            XmlUtil.deleteNovelInfoFromXml(novel) ;
            e.printStackTrace();
            return false ;
        }
    }
 
    /**
     * 从config/novelsInfo.xml中删除与novel对象相对应的的novel标签,根据ID号判断是否相同
     * 
     * @param novel
     *            小说对象
     */
    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小说对象
     */
    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,檔案操作功能類別的範例程式碼詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JSON,XML和數據格式:比較RSSJSON,XML和數據格式:比較RSSMay 02, 2025 am 12:20 AM

JSON、XML和RSS的主要區別在於結構和用途:1.JSON適用於簡單數據交換,結構簡潔,易於解析;2.XML適合複雜數據結構,結構嚴謹但解析複雜;3.RSS基於XML,用於內容髮布,標準化但用途有限。

故障排除XML/RSS提要:常見的陷阱和專家解決方案故障排除XML/RSS提要:常見的陷阱和專家解決方案May 01, 2025 am 12:07 AM

XML/RSS訂閱源的處理涉及解析和優化,常見問題包括格式錯誤、編碼問題和元素缺失。解決方案包括:1.使用XML驗證工具檢查格式錯誤;2.確保編碼一致性並使用chardet庫檢測編碼;3.處理元素缺失時使用默認值或跳過該元素;4.使用高效解析器如lxml和緩存解析結果以優化性能;5.注意數據一致性和安全性,防止XML注入攻擊。

解碼RSS文檔:閱讀和解釋提要解碼RSS文檔:閱讀和解釋提要Apr 30, 2025 am 12:02 AM

解析RSS文檔的步驟包括:1.讀取XML文件,2.使用DOM或SAX解析XML,3.提取標題、鏈接等信息,4.處理數據。 RSS文檔是一種基於XML的格式,用於發布更新內容,結構包含、和元素,適用於構建RSS閱讀器或數據處理工具。

RSS和XML:Web聯合組織的基石RSS和XML:Web聯合組織的基石Apr 29, 2025 am 12:22 AM

RSS和XML是網絡內容分發和數據交換的核心技術。 RSS用於發布頻繁更新的內容,XML用於存儲和傳輸數據。通過實際項目中的使用示例和最佳實踐,可以提高開發效率和性能。

RSS提要:探索XML的作用和目的RSS提要:探索XML的作用和目的Apr 28, 2025 am 12:06 AM

XML在RSSFeed中的作用是結構化數據、標準化和提供可擴展性。 1.XML使得RSSFeed的數據結構化,便於解析和處理。 2.XML提供了一種標準化的方式來定義RSSFeed的格式。 3.XML的可擴展性使得RSSFeed可以根據需要添加新的標籤和屬性。

縮放XML/RSS處理:性能優化技術縮放XML/RSS處理:性能優化技術Apr 27, 2025 am 12:28 AM

處理XML和RSS數據時,可以通過以下步驟優化性能:1)使用高效的解析器如lxml提升解析速度;2)採用SAX解析器減少內存使用;3)利用XPath表達式提高數據提取效率;4)實施多進程並行處理提升處理速度。

RSS文檔格式:探索RSS 2.0及以後RSS文檔格式:探索RSS 2.0及以後Apr 26, 2025 am 12:22 AM

RSS2.0是一種開放標準,允許內容髮布者以結構化的方式分發內容。它包含了豐富的元數據,如標題、鏈接、描述、發布日期等,使得訂閱者能夠快速瀏覽和訪問內容。 RSS2.0的優勢在於其簡潔和擴展性。例如,它允許自定義元素,這意味著開發者可以根據需求添加額外的信息,如作者、分類等。

理解RSS:XML觀點理解RSS:XML觀點Apr 25, 2025 am 12:14 AM

RSS是一種基於XML的格式,用於發布經常更新的內容。 1.RSSfeed通過XML結構化組織信息,包括標題、鏈接、描述等。 2.創建RSSfeed需按照XML結構編寫,添加元數據如語言和發布日期。 3.高級用法可包含多媒體文件和分類信息。 4.調試時使用XML驗證工具,確保必需元素存在且編碼正確。 5.優化RSSfeed可通過分頁、緩存和保持結構簡潔來實現。通過理解和應用這些知識,可以有效管理和分發內容。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版