你的位置:首页 > Java教程

[Java教程]xml、文件操作功能类


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

FileUtil.

 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 cy12  *13  * @date 2015年7月24日 上午8:38:3814  *15  * @Description 关于文件的一些工具16 */17 public class FileUtils {18   /**19    * 将文件中所有内容读取到字符串中20    * 21    * @param filePath22    *      文件路径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、-6534     */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 content63    *      字符串内容64    * @param filePath65    *      文件路径66    * @throws IOException67   */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 }

 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. 11 import javax. 12 import javax. 13 import javax. 14 import javax. 15 import javax. 16 import javax. 17 import javax. 18 import javax. 19 import javax. 20 import javax. 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. 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 关于 38 */ 39 public class  40   /** 41    * 目标 42    *  43    * @param user 44    *      将要被写入 45    * @return 是否成功 46   */ 47   public static boolean writeUserTo 48     try { 49       Document doc = getDocumentFrom); 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.); 66       return true; 67     } catch (Exception e) { 68       e.printStackTrace(); 69       return false; 70     } 71   } 72  73   /** 74    *  75    * @param doc 76    *       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. 98    *  99    * @return 加载后的对象100   */101   public static Map<String, User> initUser() {102     InitUser.users = new HashMap<String, User>();103     try {104       Document doc = getDocumentFrom);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) (userElement109             .getElementsByTagName("name").item(0))).getFirstChild()110             .getNodeValue();111         String passwd = ((Element) (userElement112             .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    * 从125    * 126    * @return server.127   */128   public static int getServerPort() {129     try {130       Document doc = getDocumentFrom);131       int serverPort = Integer.parseInt(doc132           .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 144    *      145    * @return 这个146    * @throws SAXException147    * @throws IOException148    * @throws ParserConfigurationException149   */150   public static Document getDocumentFrom151       throws SAXException, IOException, ParserConfigurationException {152     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();153     DocumentBuilder builder = factory.newDocumentBuilder();154     Document doc = builder.parse(155     return doc;156   }157 158   /**159    * 读取160    * 161    * @param novelId162    *      小说id163    * @return 小说列表164    * @throws ParserConfigurationException 165    * @throws IOException 166    * @throws SAXException 167   */168   public static List<Novel> getNovelListFromthrows SAXException, IOException, ParserConfigurationException {169     List<Novel> novelList = new ArrayList<Novel>();170     Document doc = getDocumentFrom171     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.192    * @param novel 小说对象193    * @return 是否写入成功 194    * TODO:确定原子操作195   */196   public static boolean writeNovelToFile(Novel novel ) {197     /**198      * 先将小说内容写入到novel文件夹下,再将小说信息写入到config/novelsInfo.199     */200     try{201       FileUtils.writeStringToFile(novel.getContent(), "novel/" + novel.getName() + ".txt");202       203       return true ;204     }catch(Exception e ){205       /**206        * 如果写入小说到文件中出现问题,要将已经写入的信息删除207        * 这段代码应该很少执行到 ~~~~208        * 209       */210       System.out.println("小说写入文件失败,正在回滚~~");211       FileUtils.deleteFile("novel/" + novel.getName() + ".txt") ;212       213       e.printStackTrace();214       return false ;215     }216   }217 218   /**219    * 从config/novelsInfo.220    * 221    * @param novel222    *      小说对象223   */224   public static void deleteNovelInfoFrom225     try {226       Document doc = getDocumentFrom);227       Element novelsElement = (Element) doc228           .getElementsByTagName("novels").item(0);229       NodeList novelElements = novelsElement230           .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.);244     } catch (Exception e) {245       e.printStackTrace();246     }247   }248   /**249    * 将小说信息写入到config/novelsInfo.250    * @param novel小说对象251   */252   public static void writeNovelInfoTo253     Document doc = null ;254     try {255       doc = getDocumentFrom);256     } catch (Exception e) {257       e.printStackTrace();258       return ;259     }260     Element novelDocument = (Element)doc.createElement("novel") ;261     // id262     Element novelIdDocument = (Element)doc.createElement("id") ;263     Text novelIdTextNode = doc.createTextNode("idValue") ;264     novelIdTextNode.setNodeValue(String.valueOf(novel.getId()));265     novelIdDocument.appendChild(novelIdTextNode);266     // name267     Element novelNameDocument = (Element)doc.createElement("name") ;268     Text novelNameTextNode = doc.createTextNode("nameValue") ;269     novelNameTextNode.setNodeValue(String.valueOf(novel.getName()));270     novelNameDocument.appendChild(novelNameTextNode);271     // author272     Element novelAuthorDocument = (Element)doc.createElement("author") ;273     Text novelAuthorTextNode = doc.createTextNode("authorValue") ;274     novelAuthorTextNode.setNodeValue(String.valueOf(novel.getAuthor()));275     novelAuthorDocument.appendChild(novelAuthorTextNode);276     // category277     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.);296     } catch (Exception e) {297       e.printStackTrace();298     }299   }300 }