search
HomeBackend DevelopmentXML/RSS Tutorialxml, detailed explanation of sample code of file operation function class

I used it in a project. The methods in it are not very general, but you can find some useful codes in it. I will slowly add and update them in the future:

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();
        }
    }
}

The above is the detailed content of xml, detailed explanation of sample code of file operation function class. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
RSS in XML: Unveiling the Core of Content SyndicationRSS in XML: Unveiling the Core of Content SyndicationApr 22, 2025 am 12:08 AM

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

Beyond the Basics: Advanced RSS Document FeaturesBeyond the Basics: Advanced RSS Document FeaturesApr 21, 2025 am 12:03 AM

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

The XML Backbone: How RSS Feeds are StructuredThe XML Backbone: How RSS Feeds are StructuredApr 20, 2025 am 12:02 AM

RSSfeedsuseXMLtostructurecontentupdates.1)XMLprovidesahierarchicalstructurefordata.2)Theelementdefinesthefeed'sidentityandcontainselements.3)elementsrepresentindividualcontentpieces.4)RSSisextensible,allowingcustomelements.5)Bestpracticesincludeusing

RSS & XML: Understanding the Dynamic Duo of Web ContentRSS & XML: Understanding the Dynamic Duo of Web ContentApr 19, 2025 am 12:03 AM

RSS and XML are tools for web content management. RSS is used to publish and subscribe to content, and XML is used to store and transfer data. They work with content publishing, subscriptions, and update push. Examples of usage include RSS publishing blog posts and XML storing book information.

RSS Documents: The Foundation of Web SyndicationRSS Documents: The Foundation of Web SyndicationApr 18, 2025 am 12:04 AM

RSS documents are XML-based structured files used to publish and subscribe to frequently updated content. Its main functions include: 1) automated content updates, 2) content aggregation, and 3) improving browsing efficiency. Through RSSfeed, users can subscribe and get the latest information from different sources in a timely manner.

Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor