Although Google's guava a certain encapsulation of Java IO operations, but it is more in favor of the collection, concurrency and caching, in the actual project, I like guava very much, I also like the Apache Toolkit Org.apache.commons.io, which provides a very powerful tool capability that simplifies code logic, improves development efficiency and quality, and is a toolkit that every Java programmer should master. This article briefly introduce Org.apache.commons.io, detailed can refer to its API note, this article most of the content is translated from http://www.javacodegeeks.com/2014/10/ apache-commons-io-tutorial.html, interested in viewing the original text, please visit the source code
Apache Commons io is a toolkit for Apache Open source, which encapsulates common operations on Io, allowing developers to perform a large number of IO operations with only a small amount of code, this article mainly describes the following several tool classes
- Utility classes
- Input
- Output
- Filters
- Comparators
- File Monitor
Currently the org.apache.commons.io2.4 version is not hosted in the MAVEN library, so you need to download it yourself and add the downloaded Commons-io-2.4.jar to the environment variable
1, Utils ( Fileutils,filenameutils,filesystemutils) These three classes mainly provide the operation of files, filenames and file system, the API is very simple, through the API name can know its role,
Examples such as the following
File absolute path private static final String Example_txt_path = "/users/fly/work/github/algorithm/src/main/java/com /fly/practice/apachecommonsio/commonio.txt "; File parent Directory private static final String Parent_dir = "/users/fly/work/github/algorithm/src/main/java/com/fly/pra Ctice/apachecommonsio "; public static void Runexample () throws IOException {System.out.println ("Utility Classes example ..."); Filenameutils Class Example//Get the full path System.out.println ("Total Path of Exampletxt:" + Fil Enameutils.getfullpath (Example_txt_path)); Gets the name System.out.println ("Full name of Exampletxt:" + filenameutils.getname (Example_txt_path)); Get extension System.out.println ("Extension of Exampletxt:" + filenameutils.getextension (example_txt_ PATH)); System.out.println ("Base Name of Exampletxt:" + filenameutils.getbasename (Example_txt_path)); The Fileutils class example//Creates a File object by Fileutils.getfile (String) and then according to Fileutils.lineiterator (file)/ /Get row iterator File examplefile = Fileutils.getfile (Example_txt_path); Lineiterator iter = Fileutils.lineiterator (examplefile); System.out.println ("Contents of Exampletxt ..."); while (Iter.hasnext ()) {System.out.println ("\ T" + iter.next ()); } iter.close (); Whether the directory already contains files file parent = Fileutils.getfile (Parent_dir); SYSTEM.OUT.PRINTLN ("Parent directory contains Exampletxt file:" + fileutils.directorycontains (parent, exam Plefile)); Iocase class example String str1 = "This is a new string."; String str2 = "This is another new String, yes!"; System.out.println ("Ends with string (case sensitive):" + IOCase.SENSITIVE.checkEndsWith (str1, "string.") ); System.out.println ("Ends with string (case InsensitiVE): "+ IOCase.INSENSITIVE.checkEndsWith (str1," string. ")); System.out.println ("String Equality:" + IOCase.SENSITIVE.checkEquals (str1, str2)); Filesystemutils Class Example System.out.println ("Free disk space (in KB):" + filesystemutils.freespacekb ("/users")); SYSTEM.OUT.PRINTLN ("Free disk Space" (in MB): "+ filesystemutils.freespacekb ("/users ")/1024); }
2, InputStream, which provides the Xmlstreamreader tool class, the ability to obtain XML file encoding and other operations,
Examples such as the following
private static final String Xml_path = "/users/fly/work/github/algorithm/src/main/java/com/fly/practice/ Apachecommonsio/test.xml "; public static void Runexample () { System.out.println ("Input example ..."); Xmlstreamreader xmlReader = null; try { //Xmlstreamreader: Reads an XML file that provides a file encoding API for the past files XML = Fileutils.getfile (Xml_path); XmlReader = new Xmlstreamreader (XML); SYSTEM.OUT.PRINTLN ("XML Encoding:" + xmlreader.getencoding ()); } catch (IOException e) { e.printstacktrace (); } finally { try {xmlreader.close ();} catch (IOException e) {e.printstacktrace ();} } }
3, output, the Teeinputstream,teeoutputstream class provides the ability to quickly copy the input stream into the output stream
private static final String INPUT = "This should go to the output."; public static void Runexample () {System.out.println ("Output example ..."); Teeinputstream Tee=null; Teeinputstream Teein = null; Teeoutputstream teeout = null; Try {//teeinputstream can quickly copy an input stream into the output stream bytearrayinputstream in = new Bytearrayinputstream (input.getbyt ES ("Us-ascii")); Bytearrayoutputstream out = new Bytearrayoutputstream (); Tee = new Teeinputstream (in, out, true); Tee.read (New Byte[input.length ()]); System.out.println ("Output stream:" + out.tostring ()); The input stream can be copied simultaneously to two output streams bytearrayoutputstream out1 = new Bytearrayoutputstream (); Bytearrayoutputstream out2 = new Bytearrayoutputstream (); Teeout = new Teeoutputstream (OUT1, OUT2); Teein = new Teeinputstream (in, Teeout, true); Teein.read (New Byte[input.length ()]); System.out.println ("Output Stream 1:" + out1.tostring ()); System.out.println ("Output Stream 2:" + out2.tostring ()); } catch (IOException e) {e.printstacktrace (); } finally {//here does not need to close teeout, when Teein is closed, the teeout try {teein.close () is also closed; Tee.close ();} catch (IOException e) {e.printstacktrace ();} } }
4, Filters,commons-io provides a variety of filters, can filter the files under the specified directory according to the conditions, but also supports the filter combination,
Examples such as the following
private static final String Parent_dir = "/users/fly/work/github/algorithm/src/main/java/com/fly/practice/apac Hecommonsio "; public static void Runexample () {System.out.println ("File Filter example ..."); Namefilefilter: Gets the file that matches the given file list in the specified directory//For example, gets the Parent_dir directory under Commonios and commonio.txt file dir = FileUtils. GetFile (Parent_dir); String[] Acceptednames = {"Commonios", "Commonio.txt"}; For (String file:dir.list (New Namefilefilter (Acceptednames, iocase.insensitive))) {System.out.println ("File F Ound, named: "+ file); //wildcardfilefilter: Supports regular matching, gets the file for which the regular is satisfied under the specified directory for (String file:dir.list (New Wildcardfilefil ter ("*common*")) {System.out.println ("Wildcard file found, named:" + file); }//Prefixfilefilter: Gets the file name prefixed with the given string for (string file:dir.list (New Prefixfilefilter ("Commo n "))) {System.out.println (" Prefix file found, named: "+ file"); }//Suffixfilefilter:: Gets the filename with the given string suffix for (string file:dir.list ("New Suffixfilefilter" (". txt ")) {System.out.println (" Suffix file found, named: "+ file); }//Orfilefilter: Support for passing in multiple filters, the relationship between filters is or for (String file:dir.list (New Orfilefilter ( New Wildcardfilefilter ("*ample*"), New Suffixfilefilter (". txt"))) {System.out.println ("Or file found, Named: "+ file"; }//andfilefilter: Supports incoming multiple filters, the relationship between filters is and for (String file:dir.list (New Andfilefilter ( New Wildcardfilefilter ("*ample*"), New Notfilefilter (New Suffixfilefilter (". txt")))) {Syste M.out.println ("And/not file found, named:" + file); } }
5, Comparators,commons-io provides a variety of file Comparison tool class, can be based on file name, file size, modification time and other files in the directory to sort,
A simple example is the following
private static final String Parent_dir = "/users/fly/work/github/algorithm/src/main/java/com/fly/practice/apach Ecommonsio "; private static final String file_1 = "/users/fly/work/github/algorithm/src/main/java/com/fly/practice/apachecom Monsio/commonio.txt "; private static final String file_2 = "/users/fly/work/github/algorithm/src/main/java/com/fly/practice/apachecom Monsio/test.xml "; public static void Runexample () {System.out.println ("Comparator example ..."); Namefilecomparator: Sorted by file name, Iocase indicates if case sensitive file Parentdir = Fileutils.getfile (Parent_dir); Namefilecomparator comparator = new Namefilecomparator (iocase.sensitive); file[] Sortedfiles = Comparator.sort (Parentdir.listfiles ()); System.out.println ("Sorted by name, files in parent directory:"); for (File file:sortedfiles) {System.out.println ("\ T" + file.getabsolutepath ()); } Sizefilecomparator: According to the size of the file, small files in front, its constructor supports passing a Boolean parameter,//true represents the need to calculate the directory size under this directory//flase that you do not need to calculate the Directory size under directory (0) Sizefilecomparator sizecomparator = new Sizefilecomparator (true); file[] Sizefiles = Sizecomparator.sort (Parentdir.listfiles ()); System.out.println ("Sorted by size files in parent directory:"); for (File file:sizefiles) {System.out.println ("\ T" + file.getname () + "with size (KB):" + file.length ()); }//Lastmodifiedfilecomparator: According to the modified time, the latest modification lastmodifiedfilecomparator Lastmodifie D = new Lastmodifiedfilecomparator (); file[] Lastmodifiedfiles = Lastmodified.sort (Parentdir.listfiles ()); System.out.println ("Sorted by the last modified files in parent directory:"); for (File file:lastmodifiedfiles) {Date modified = new Date (file.lastmodified ()); System.out.println ("\ T" + file.getname () + "Last Modified on:" + Modified); } }
6, File Monitor,commons-io also provides a directory monitoring class, you can monitor the specified directory, if the file changes in the directory (modify, add, delete, etc.), its monitoring will send the appropriate event to the listener.
Examples such as the following
private static final String Example_path = "/users/fly/work/github/algorithm/src/main/java/com/fly/practice/apa Checommonsio/commonio.txt "; private static final String Parent_dir = "/users/fly/work/github/algorithm/src/main/java/com/fly/practice/apach Ecommonsio "; private static final String New_dir = "/users/fly/work/github/algorithm/src/main/java/com/fly/practice/apacheco Mmonsio/newdir "; private static final String New_file = "/users/fly/work/github/algorithm/src/main/java/com/fly/practice/apachec Ommonsio/newfile.txt "; public static void Runexample () {System.out.println ("File Monitor example ..."); Fileentry//We can monitor changes and get information about files//using the methods of this Class. Fileentry entry = new Fileentry (Fileutils.getfile (Example_path)); System.out.println ("File Monitored:" + entry.getfile ()); System.out.priNtln ("File name:" + entry.getname ()); System.out.println ("is the file a directory?:" + entry.isdirectory ()); File (directory) monitoring//Create observers for the specified directory and add listeners to respond to the event file Parentdir = Fileutils.getfile (Parent_dir); Filealterationobserver observer = new Filealterationobserver (parentdir); Observer.addlistener (New Filealterationlisteneradaptor () {@Override public void Onfilecreate (file file) {System.out.println ("file created:" + file.getname ()); } @Override public void Onfiledelete (file file) {System. Out.println ("File deleted:" + File.getname ()); } @Override public void Ondirectorycreate (File dir) {Sys Tem.out.println ("Directory created:" + dir.getname ()); } @OveRride public void Ondirectorydelete (File dir) {System.out.println ("Directory deleted:" + Dir.getname ()); } }); Create a monitor that checks every 500 milliseconds filealterationmonitor monitor = new Filealterationmonitor (Observer); try {monitor.start (); After start monitoring, do some file operation to the monitoring directory, trigger listener file Newdir = new file (New_dir); File NewFile = new file (new_file); Newdir.mkdirs (); Newfile.createnewfile (); Thread.Sleep (1000); FileDeleteStrategy.NORMAL.delete (Newdir); FileDeleteStrategy.NORMAL.delete (NewFile); Thread.Sleep (1000); Monitor.stop (); } catch (IOException e) {e.printstacktrace (); } catch (Interruptedexception e) {e.printstacktrace (); } catch (Exception e) {e.printstacktrace (); } }
The above is just a brief introduction to Commons-io, from which we can see that the toolkit provides powerful IO operations and more features that need to be explored in real-world projects
Apache Commons IO Introduction