I used it in a project. the methods in it are not too common, but some useful code can be found in it. I will add some updates later: What I used in a project, the method is not too common, but some useful code can be found in it, and the updates will be added later:
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 8:38:38 on October 11, July 24, 2015 ** @ Description some tools for file */public class FileUtils {/*** read all the content in the file * @ param filePath * file path * @ return file content */public static String getStringFromFil in the String E (String filePath) {File file = new File (filePath); if (! File. exists () {return "";}/*** handle file read garbled problem: * as long as two common encodings are identified: GBK and UTF-8. Because the default English windows encoding is GBK, so generally as long as the determination of UTF-8 encoding format. * For text files in UTF-8 encoding format, the values of the first three bytes are-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; // This method obtains the object's byte length, // and I want to create a char array. char occupies two bytes, // byte one byte, so dividing by 2 indicates the character length of the file char [] filecontent = new char [filelength. intValue ()]; read. read (filecontent); return new String (filecontent);} catch (Exception e) {e. printStackTrace (); return "";}} /*** write the string to the file ** @ param content * string content * @ param filePath * file path * @ throws IOException */public stati C void writeStringToFile (String content, String filePath) throws IOException {File file File = new File (filePath); if (! File. exists () {file. createNewFile ();} FileOutputStream out = new FileOutputStream (file); out. write (content. getBytes (); out. close ();}/*** delete the specified File * @ param filePath file path */public static void deleteFile (String filePath) {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 3:19:06 on April 9, July 23, 2015 ** @ Description about xml operations */public class XmlUtil {/*** the target xml is config/users. xml ** @ param user * User object to be written into xml * @ return: Successful? */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 * Document object in XML * @ param filePath * output file path * @ throws TransformerFactoryConfigurationError * @ throws TransformerConfigurationException * @ throws TransformerException */private static void writeDocumentToFile (Document doc, string filePath) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException {// write to the hard disk TransformerFactory tFactory = TransformerFactory. newInstance (); Transformer transformer = tFactory. newTransformer ();/** encoding */transformer. setOutputProperty (OutputKeys. ENCODING, "UTF-8"); DOMSource source = new DOMSource (doc); StreamResult result = new StreamResult (new File (filePath); transformer. transform (source, result);}/*** Load config/users. in xml, user information is sent to the object ** @ return loaded object */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 ;}}/*** get the server running Port from xml *** @ return server. port number */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 * Location of the xml file * @ return the Document object corresponding to the xml file * @ 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 ;} /*** read the information in xml to the List ** @ param novelId * novel id * @ return novel List * @ throws ParserConfigurationException * @ throws IOException * @ throws SAXException */ 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 = n Ovel. 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 ;}/** * Write Novel information to config/novelsInfo. xml and write the novel content to the novel folder * @ param Novel novel object * @ return write successful * TODO: confirm atomic operation */public static boolean writeNovelToFile (novel) {/*** write the novel content to the novel folder, and then write the novel information to config/novelsInfo. xml */try {FileUtils. writeStringToFile (novel. getContent (), "novel/" + novel. getName () + ". txt "); XmlUtil. writeNovelInfoToXml (novel); return true;} catch (Exception e) {/*** if a novel is written If a problem occurs in the file, delete the information that has been written * this code should be rarely executed ~~~~ **/System. out. println ("failed to write the novel into the file, rolling back ~~ "); FileUtils. deleteFile ("novel/" + novel. getName () + ". txt "); XmlUtil. deleteNovelInfoFromXml (novel); e. printStackTrace (); return false ;}}/*** from config/novelsInfo. delete the novel tag corresponding to the novel object in xml, and determine whether it is the same according to the ID number ** @ param novel * Novel object */public static void deleteNovelInfoFromXml (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 () ;}}/*** writes the novel information to config/novelsInfo. * @ param novel Novel object */public static void writeNovelInfoToXml (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); // write to the file try {writeDocumentToFile (doc, "config/novelsInfo. xml ");} catch (Exception e) {e. printStackTrace ();}}}
The above is the detailed content of the sample code for file operation function classes. For more information, see other related articles in the first PHP community!