栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > 其他 > xml语言

xml,文件操作功能类的示例代码详解

xml语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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; public class FileUtils {        public static String getStringFromFile(String filePath) {        File file = new File(filePath) ;        if(!file.exists()){             return "" ;        }                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 "" ;        }    }         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();    }        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; public class XmlUtil {        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;        }    }         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);    }         public static Map initUser() {        InitUser.users = new HashMap();        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;        }    }         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;        }    }         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;    }         public static List getNovelListFromXml(String filePath) throws SAXException, IOException, ParserConfigurationException {        List novelList = new ArrayList();        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 ;    }        public static boolean writeNovelToFile(Novel novel ) {                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 ;        }    }         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();        }    }        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,文件操作功能类的示例代码详解的详细内容,更多请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/794535.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号