zoukankan      html  css  js  c++  java
  • xml、文件操作功能类

    我一个项目中用到的,里面的方法不是太通用,但是可以从里面找到一些有用的代码,以后慢慢添补更新:

    FileUtil.xml

     1 package com.novel.util;
     2 
     3 import java.io.File;
     4 import java.io.FileInputStream;
     5 import java.io.FileOutputStream;
     6 import java.io.IOException;
     7 import java.io.InputStream;
     8 import java.io.InputStreamReader;
     9 
    10 /**
    11  * @author cy
    12  *
    13  * @date 2015年7月24日 上午8:38:38
    14  *
    15  * @Description 关于文件的一些工具
    16  */
    17 public class FileUtils {
    18     /**
    19      * 将文件中所有内容读取到字符串中
    20      * 
    21      * @param filePath
    22      *            文件路径
    23      * @return 文件内容
    24      */
    25     public static String getStringFromFile(String filePath) {
    26         File file = new File(filePath) ;
    27         if(!file.exists()){
    28              return "" ;
    29         }
    30         /**
    31          * 处理文件读取乱码问题 :
    32          * 只要判定两种常见的编码就可以了:GBK和UTF-8。由于中文Windows默认的编码是GBK,所以一般只要判定UTF-8编码格式。
    33             *对于UTF-8编码格式的文本文件,其前3个字节的值就是-17、-69、-65
    34          */
    35         try{
    36             byte[] firstThreeByte = new byte[3] ;
    37             InputStream in = new FileInputStream(file) ;
    38             in.read(firstThreeByte) ;
    39             in.close() ;
    40             String encoding = "" ;
    41             if(firstThreeByte[0] == -17 && firstThreeByte[1] == -16 && firstThreeByte[2] == -65){
    42                 encoding = "utf-8" ;
    43             }else{
    44                 encoding = "gbk" ;
    45             }
    46              InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);      
    47             Long filelength = file.length() / 2 ; // 该方法获取的是文件字节长度,
    48                                                   //而我要创建的是char数组,char占两个字节,
    49                                                   //byte一个字节,所以除以2表示的是该文件的字符长度
    50             char[] filecontent = new char[filelength.intValue()] ; 
    51             read.read(filecontent) ;
    52             return new String(filecontent) ;
    53         }catch(Exception e ){
    54             e.printStackTrace();
    55             return "" ;
    56         }
    57     }
    58 
    59     /**
    60      * 将字符串写入文件
    61      * 
    62      * @param content
    63      *            字符串内容
    64      * @param filePath
    65      *            文件路径
    66      * @throws IOException
    67      */
    68     public static void writeStringToFile(String content, String filePath)
    69             throws IOException {
    70 
    71         File file = new File(filePath);
    72         if (!file.exists()) {
    73             file.createNewFile();
    74         }
    75         FileOutputStream out = new FileOutputStream(file);
    76         out.write(content.getBytes());
    77         out.close();
    78     }
    79     /**
    80      * 删除指定的文件 
    81      * @param filePath文件路径 
    82      */
    83     public static void deleteFile(String filePath ) {
    84         File file = new File(filePath) ;
    85         if(file.exists()){
    86             file.delete() ;
    87         }
    88     }
    89 }

    XmlUtil.java

      1 package com.novel.util;
      2 
      3 import java.io.File;
      4 import java.io.IOException;
      5 import java.util.ArrayList;
      6 import java.util.HashMap;
      7 import java.util.List;
      8 import java.util.Map;
      9 
     10 import javax.xml.parsers.DocumentBuilder;
     11 import javax.xml.parsers.DocumentBuilderFactory;
     12 import javax.xml.parsers.ParserConfigurationException;
     13 import javax.xml.transform.OutputKeys;
     14 import javax.xml.transform.Transformer;
     15 import javax.xml.transform.TransformerConfigurationException;
     16 import javax.xml.transform.TransformerException;
     17 import javax.xml.transform.TransformerFactory;
     18 import javax.xml.transform.TransformerFactoryConfigurationError;
     19 import javax.xml.transform.dom.DOMSource;
     20 import javax.xml.transform.stream.StreamResult;
     21 
     22 import org.w3c.dom.Document;
     23 import org.w3c.dom.Element;
     24 import org.w3c.dom.Node;
     25 import org.w3c.dom.NodeList;
     26 import org.w3c.dom.Text;
     27 import org.xml.sax.SAXException;
     28 
     29 import com.novel.entity.Novel;
     30 import com.novel.entity.User;
     31 
     32 /**
     33  * @author cy
     34  *
     35  * @date 2015年7月23日 下午3:19:06
     36  *
     37  * @Description 关于xml的操作
     38  */
     39 public class XmlUtil {
     40     /**
     41      * 目标xml为 config/users.xml
     42      * 
     43      * @param user
     44      *            将要被写入xml的User对象
     45      * @return 是否成功
     46      */
     47     public static boolean writeUserToXml(User user) {
     48         try {
     49             Document doc = getDocumentFromXml("config/users.xml");
     50             Element newUserElement = doc.createElement("user");
     51             Element newUsernameElement = doc.createElement("name");
     52             Text nameTextNode = doc.createTextNode("nameValue");
     53             nameTextNode.setNodeValue(user.getName());
     54             newUsernameElement.appendChild(nameTextNode);
     55             Element newUserPwdElement = doc.createElement("pwd");
     56             Text pwdTextNode = doc.createTextNode("pwdValue");
     57             pwdTextNode.setNodeValue(user.getName());
     58             newUserPwdElement.appendChild(pwdTextNode);
     59             newUserElement.appendChild(newUsernameElement);
     60             newUserElement.appendChild(newUserPwdElement);
     61             Element usersElement = (Element) doc.getElementsByTagName("users")
     62                     .item(0);
     63             usersElement.appendChild(newUserElement);
     64 
     65             writeDocumentToFile(doc, "config/users.xml");
     66             return true;
     67         } catch (Exception e) {
     68             e.printStackTrace();
     69             return false;
     70         }
     71     }
     72 
     73     /**
     74      * 
     75      * @param doc
     76      *            XML中的Document对象
     77      * @param filePath
     78      *            输出的文件路径
     79      * @throws TransformerFactoryConfigurationError
     80      * @throws TransformerConfigurationException
     81      * @throws TransformerException
     82      */
     83     private static void writeDocumentToFile(Document doc, String filePath)
     84             throws TransformerFactoryConfigurationError,
     85             TransformerConfigurationException, TransformerException {
     86         // 写入到硬盘
     87         TransformerFactory tFactory = TransformerFactory.newInstance();
     88         Transformer transformer = tFactory.newTransformer();
     89         /** 编码 */
     90         transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
     91         DOMSource source = new DOMSource(doc);
     92         StreamResult result = new StreamResult(new File(filePath));
     93         transformer.transform(source, result);
     94     }
     95 
     96     /**
     97      * 加载config/users.xml中用户信息到对象中
     98      * 
     99      * @return 加载后的对象
    100      */
    101     public static Map<String, User> initUser() {
    102         InitUser.users = new HashMap<String, User>();
    103         try {
    104             Document doc = getDocumentFromXml("config/users.xml");
    105             NodeList usersNodeList = doc.getElementsByTagName("user");
    106             for (int i = 0; i < usersNodeList.getLength(); i++) {
    107                 Element userElement = (Element) usersNodeList.item(i);
    108                 String userName = ((Element) (userElement
    109                         .getElementsByTagName("name").item(0))).getFirstChild()
    110                         .getNodeValue();
    111                 String passwd = ((Element) (userElement
    112                         .getElementsByTagName("pwd").item(0))).getFirstChild()
    113                         .getNodeValue();
    114                 InitUser.users.put(userName, new User(userName, passwd));
    115             }
    116         } catch (Exception e) {
    117             e.printStackTrace();
    118         } finally {
    119             return InitUser.users;
    120         }
    121     }
    122 
    123     /**
    124      * 从xml中获取服务器运行的端口
    125      * 
    126      * @return server.xml文件中的端口号
    127      */
    128     public static int getServerPort() {
    129         try {
    130             Document doc = getDocumentFromXml("config/server.xml");
    131             int serverPort = Integer.parseInt(doc
    132                     .getElementsByTagName("server-port").item(0)
    133                     .getFirstChild().getNodeValue());
    134             return serverPort;
    135         } catch (Exception e) {
    136             e.printStackTrace();
    137             return 0;
    138         }
    139     }
    140 
    141     /**
    142      * 
    143      * @param xmlPath
    144      *            xml文件的位置
    145      * @return 这个xml文件相应的Document对象
    146      * @throws SAXException
    147      * @throws IOException
    148      * @throws ParserConfigurationException
    149      */
    150     public static Document getDocumentFromXml(String xmlPath)
    151             throws SAXException, IOException, ParserConfigurationException {
    152         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    153         DocumentBuilder builder = factory.newDocumentBuilder();
    154         Document doc = builder.parse(xmlPath);
    155         return doc;
    156     }
    157 
    158     /**
    159      * 读取xml中小说的信息到List中
    160      * 
    161      * @param novelId
    162      *            小说id
    163      * @return 小说列表
    164      * @throws ParserConfigurationException 
    165      * @throws IOException 
    166      * @throws SAXException 
    167      */
    168     public static List<Novel> getNovelListFromXml(String filePath) throws SAXException, IOException, ParserConfigurationException {
    169         List<Novel> novelList = new ArrayList<Novel>();
    170         Document doc = getDocumentFromXml(filePath);
    171         NodeList novels = doc.getElementsByTagName("novel");
    172         for (int i = 0; i < novels.getLength(); i++) {
    173             Element novel = ((Element) novels.item(i));
    174             int id = Integer.parseInt(novel.getElementsByTagName("id").item(0)
    175                     .getFirstChild().getNodeValue());
    176             String name = novel.getElementsByTagName("name").item(0)
    177                     .getFirstChild().getNodeValue();
    178             String author = novel.getElementsByTagName("author").item(0)
    179                     .getFirstChild().getNodeValue();
    180             String category = novel.getElementsByTagName("category").item(0)
    181                     .getFirstChild().getNodeValue();
    182             String description = novel.getElementsByTagName("description")
    183                     .item(0).getFirstChild().getNodeValue();
    184             
    185             Novel oneNovel = new Novel(id, category, name, author, description);
    186             novelList.add(oneNovel);
    187         }
    188         return novelList ;
    189     }
    190     /**
    191      * 将Novel信息写入到config/novelsInfo.xml中并且将小说内容写入到novel文件夹下
    192      * @param novel 小说对象
    193      * @return 是否写入成功 
    194      * TODO:确定原子操作
    195      */
    196     public static boolean writeNovelToFile(Novel novel ) {
    197         /**
    198          * 先将小说内容写入到novel文件夹下,再将小说信息写入到config/novelsInfo.xml中
    199          */
    200         try{
    201             FileUtils.writeStringToFile(novel.getContent(), "novel/" + novel.getName() + ".txt");
    202             XmlUtil.writeNovelInfoToXml(novel) ;
    203             return true ;
    204         }catch(Exception e ){
    205             /**
    206              * 如果写入小说到文件中出现问题,要将已经写入的信息删除
    207              * 这段代码应该很少执行到 ~~~~
    208              * 
    209              */
    210             System.out.println("小说写入文件失败,正在回滚~~");
    211             FileUtils.deleteFile("novel/" + novel.getName() + ".txt") ;
    212             XmlUtil.deleteNovelInfoFromXml(novel) ;
    213             e.printStackTrace();
    214             return false ;
    215         }
    216     }
    217 
    218     /**
    219      * 从config/novelsInfo.xml中删除与novel对象相对应的的novel标签,根据ID号判断是否相同
    220      * 
    221      * @param novel
    222      *            小说对象
    223      */
    224     public static void deleteNovelInfoFromXml(Novel novel) {
    225         try {
    226             Document doc = getDocumentFromXml("config/novelsInfo.xml");
    227             Element novelsElement = (Element) doc
    228                     .getElementsByTagName("novels").item(0);
    229             NodeList novelElements = novelsElement
    230                     .getElementsByTagName("novel");
    231 
    232             Node deleteElement = null;
    233             for (int i = 0; i < novelElements.getLength(); i++) {
    234                 String id = ((Element) novelElements.item(i))
    235                         .getElementsByTagName("id").item(0).getFirstChild()
    236                         .getNodeValue();
    237                 if (id.equals(String.valueOf(novel.getId()))) {
    238                     deleteElement = novelElements.item(i);
    239                     break;
    240                 }
    241             }
    242             novelsElement.removeChild(deleteElement);
    243             writeDocumentToFile(doc, "config/novlesInfo.xml");
    244         } catch (Exception e) {
    245             e.printStackTrace();
    246         }
    247     }
    248     /**
    249      * 将小说信息写入到config/novelsInfo.xml文件中
    250      * @param novel小说对象
    251      */
    252     public static void writeNovelInfoToXml(Novel novel){
    253         Document doc = null ;
    254         try {
    255             doc = getDocumentFromXml("config/novelsInfo.xml");
    256         } catch (Exception e) {
    257             e.printStackTrace();
    258             return ;
    259         }
    260         Element novelDocument = (Element)doc.createElement("novel") ;
    261         // id
    262         Element novelIdDocument = (Element)doc.createElement("id") ;
    263         Text novelIdTextNode = doc.createTextNode("idValue") ;
    264         novelIdTextNode.setNodeValue(String.valueOf(novel.getId()));
    265         novelIdDocument.appendChild(novelIdTextNode);
    266         // name
    267         Element novelNameDocument = (Element)doc.createElement("name") ;
    268         Text novelNameTextNode = doc.createTextNode("nameValue") ;
    269         novelNameTextNode.setNodeValue(String.valueOf(novel.getName()));
    270         novelNameDocument.appendChild(novelNameTextNode);
    271         // author
    272         Element novelAuthorDocument = (Element)doc.createElement("author") ;
    273         Text novelAuthorTextNode = doc.createTextNode("authorValue") ;
    274         novelAuthorTextNode.setNodeValue(String.valueOf(novel.getAuthor()));
    275         novelAuthorDocument.appendChild(novelAuthorTextNode);
    276         // category
    277         Element novelCategoryDocument = (Element)doc.createElement("category") ;
    278         Text novelCategoryTextNode = doc.createTextNode("categoryValue") ;
    279         novelCategoryTextNode.setNodeValue(String.valueOf(novel.getCategory()));
    280         novelCategoryDocument.appendChild(novelCategoryTextNode);
    281         // description 
    282         Element novelDescriptionDocument = (Element)doc.createElement("description") ;
    283         Text novelDescriptionTextNode = doc.createTextNode("descriptionValue") ;
    284         novelDescriptionTextNode.setNodeValue(String.valueOf(novel.getDescription()));
    285         novelDescriptionDocument.appendChild(novelDescriptionTextNode);
    286         
    287         novelDocument.appendChild(novelIdDocument) ;
    288         novelDocument.appendChild(novelNameDocument) ;
    289         novelDocument.appendChild(novelAuthorDocument) ;
    290         novelDocument.appendChild(novelCategoryDocument) ;
    291         novelDocument.appendChild(novelDescriptionDocument) ;
    292         doc.getElementsByTagName("novels").item(0).appendChild(novelDocument) ;
    293         // 写到文件中
    294         try {
    295             writeDocumentToFile(doc, "config/novelsInfo.xml");
    296         } catch (Exception e) {
    297             e.printStackTrace();
    298         }
    299     }
    300 }
  • 相关阅读:
    Git的使用---6. 分支管理
    Git的使用---5. 工作区、暂存区和仓库
    虚拟机中安装 win2012 r2 tools工具 提示需要安装kb2919355
    【实验】OSPF的基本配置
    【实验】 OSPF和BFD联动
    【实验】VRRP+链路跟踪+BFD联动
    【实验】基于接口和全局DHCP
    【实验】静态LACP的链路聚合
    【实验】手工负载分担链路聚合
    【实验】vxlan的静态配置
  • 原文地址:https://www.cnblogs.com/caiyao/p/4776769.html
Copyright © 2011-2022 走看看