Apache Commons IO 包绝对是好东西,地址在http://commons.apache.org/proper/commons-io/,下面用例子分别介绍: 
  1)  工具类 
  2) 输入 
  3) 输出 
  4) filters过滤 
  5) Comparators 
  6) 文件监控 
  
   总的入口例子为: 
  

Java代码  

apache commons io入门_工具类

    1. public class
    2.   
    3. public static void
    4.         UtilityExample.runExample();  
    5.           
    6.         FileMonitorExample.runExample();  
    7.           
    8.         FiltersExample.runExample();  
    9.           
    10.         InputExample.runExample();  
    11.           
    12.         OutputExample.runExample();  
    13.           
    14.         ComparatorExample.runExample();  
    15.     }  
    16. }



    一  工具类包UtilityExample代码: 


        这个工具类包分如下几个主要工具类: 

         1) FilenameUtils:主要处理各种操作系统下对文件名的操作 

         2) FileUtils:处理文件的打开,移动,读取和判断文件是否存在 

        3) IOCASE:字符串的比较 

        4) FileSystemUtils:返回磁盘的空间大小 


       

    Java代码  


    1. import
    2. import
    3.   
    4. import
    5. import
    6. import
    7. import
    8. import
    9.   
    10. public final class
    11.       
    12. // We are using the file exampleTxt.txt in the folder ExampleFolder,
    13. // and we need to provide the full path to the Utility classes.
    14. private static final
    15. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\exampleTxt.txt";  
    16.       
    17. private static final
    18. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample";  
    19.   
    20. public static void runExample() throws
    21. "Utility Classes example...");  
    22.           
    23.           
    24. // FilenameUtils
    25.           
    26. "Full path of exampleTxt: "
    27.                 FilenameUtils.getFullPath(EXAMPLE_TXT_PATH));  
    28.           
    29. "Full name of exampleTxt: "
    30.                 FilenameUtils.getName(EXAMPLE_TXT_PATH));  
    31.           
    32. "Extension of exampleTxt: "
    33.                 FilenameUtils.getExtension(EXAMPLE_TXT_PATH));  
    34.           
    35. "Base name of exampleTxt: "
    36.                 FilenameUtils.getBaseName(EXAMPLE_TXT_PATH));  
    37.           
    38.           
    39. // FileUtils
    40.           
    41. // We can create a new File object using FileUtils.getFile(String)
    42. // and then use this object to get information from the file.
    43.         File exampleFile = FileUtils.getFile(EXAMPLE_TXT_PATH);  
    44.         LineIterator iter = FileUtils.lineIterator(exampleFile);  
    45.           
    46. "Contents of exampleTxt...");  
    47. while
    48. "\t"
    49.         }  
    50.         iter.close();  
    51.           
    52. // We can check if a file exists somewhere inside a certain directory.
    53.         File parent = FileUtils.getFile(PARENT_DIR);  
    54. "Parent directory contains exampleTxt file: "
    55.                 FileUtils.directoryContains(parent, exampleFile));  
    56.           
    57.           
    58. // IOCase
    59.           
    60. "This is a new String.";  
    61. "This is another new String, yes!";  
    62.           
    63. "Ends with string (case sensitive): "
    64. "string."));  
    65. "Ends with string (case insensitive): "
    66. "string."));  
    67.           
    68. "String equality: "
    69.                 IOCase.SENSITIVE.checkEquals(str1, str2));  
    70.           
    71.           
    72. // FileSystemUtils
    73. "Free disk space (in KB): " + FileSystemUtils.freeSpaceKb("C:"));  
    74. "Free disk space (in MB): " + FileSystemUtils.freeSpaceKb("C:") / 1024);  
    75.     }  
    76. }




    输出: 

    Java代码  

    1. Utility Classes example...  
    2. Full path of exampleTxt: C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\  
    3. Full name of exampleTxt: exampleTxt.txt  
    4. Extension of exampleTxt: txt  
    5. Base name of exampleTxt: exampleTxt  
    6. Contents of exampleTxt...  
    7.     This is an example text file.  
    8. for
    9. Parent directory contains exampleTxt file: true
    10. Ends with string (case sensitive): false
    11. Ends with string (case insensitive): true
    12. String equality: false
    13. Free disk space (in KB): 32149292
    14. Free disk space (in MB): 31395




    二  FileMonitor工具类包 

       这个org.apache.commons.io.monitor 包中的工具类可以监视文件或者目录的变化,获得指定文件或者目录的相关信息,下面看例子: 

      

    Java代码  

    1. import
    2. import
    3.   
    4. import
    5. import
    6. import
    7. import
    8. import
    9. import
    10.   
    11.   
    12. public final class
    13.       
    14. private static final
    15. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\exampleFileEntry.txt";  
    16.       
    17. private static final
    18. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder";  
    19.       
    20. private static final
    21. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\newDir";  
    22.       
    23. private static final
    24. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\newFile.txt";  
    25.   
    26. public static void
    27. "File Monitor example...");  
    28.           
    29.           
    30. // FileEntry
    31.           
    32. // We can monitor changes and get information about files
    33. // using the methods of this class.
    34. new
    35.           
    36. "File monitored: "
    37. "File name: "
    38. "Is the file a directory?: "
    39.           
    40.           
    41. // File Monitoring
    42.           
    43. // Create a new observer for the folder and add a listener
    44. // that will handle the events in a specific directory and take action.
    45.         File parentDir = FileUtils.getFile(PARENT_DIR);  
    46.           
    47. new
    48. new
    49.               
    50. @Override
    51. public void
    52. "File created: "
    53.                 }  
    54.                   
    55. @Override
    56. public void
    57. "File deleted: "
    58.                 }  
    59.                   
    60. @Override
    61. public void
    62. "Directory created: "
    63.                 }  
    64.                   
    65. @Override
    66. public void
    67. "Directory deleted: "
    68.                 }  
    69.         });  
    70.           
    71. // Add a monior that will check for events every x ms,
    72. // and attach all the different observers that we want.
    73. new FileAlterationMonitor(500, observer);  
    74. try
    75.             monitor.start();  
    76.           
    77. // After we attached the monitor, we can create some files and directories
    78. // and see what happens!
    79. new
    80. new
    81.               
    82.             newDir.mkdirs();  
    83.             newFile.createNewFile();  
    84.                   
    85. 1000);  
    86.               
    87.             FileDeleteStrategy.NORMAL.delete(newDir);  
    88.             FileDeleteStrategy.NORMAL.delete(newFile);  
    89.               
    90. 1000);  
    91.               
    92.             monitor.stop();  
    93. catch
    94.             e.printStackTrace();  
    95. catch
    96.             e.printStackTrace();  
    97. catch
    98.             e.printStackTrace();  
    99.         }  
    100.     }  
    101. }


    输出如下: 

      

    Java代码  

    1. File Monitor example...  
    2. File monitored: C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleFileEntry.txt  
    3. File name: exampleFileEntry.txt  
    4. Is the file a directory?: false
    5. Directory created: newDir  
    6. File created: newFile.txt  
    7. Directory deleted: newDir  
    8. File deleted: newFile.txt



        上面的特性的确很赞!分析下,这个工具类包下的工具类,可以允许我们创建跟踪文件或目录变化的监听句柄,当文件目录等发生任何变化,都可以用“观察者”的身份进行观察, 

    其步骤如下: 

       1) 创建要监听的文件对象 

       2) 创建FileAlterationObserver 监听对象,在上面的例子中, 

       File parentDir = FileUtils.getFile(PARENT_DIR); 

      FileAlterationObserver observer = new FileAlterationObserver(parentDir); 

       创建的是监视parentDir目录的变化, 

       3) 为观察器创建FileAlterationListenerAdaptor的内部匿名类,增加对文件及目录的增加删除的监听 

       4) 创建FileAlterationMonitor监听类,每隔500ms监听目录下的变化,其中开启监视是用monitor的start方法即可。 


    三  过滤器 filters 

       先看例子: 

      

    Java代码  

    1. import
    2.   
    3. import
    4. import
    5. import
    6. import
    7. import
    8. import
    9. import
    10. import
    11. import
    12.   
    13. public final class
    14.       
    15. private static final
    16. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder";  
    17.   
    18. public static void
    19. "File Filter example...");  
    20.           
    21.           
    22. // NameFileFilter
    23. // Right now, in the parent directory we have 3 files:
    24. //      directory example
    25. //      file exampleEntry.txt
    26. //      file exampleTxt.txt
    27.           
    28. // Get all the files in the specified directory
    29. // that are named "example".
    30.         File dir = FileUtils.getFile(PARENT_DIR);  
    31. "example", "exampleTxt.txt"};  
    32. for (String file: dir.list(new
    33. "File found, named: "
    34.         }  
    35.           
    36.           
    37. //WildcardFileFilter
    38. // We can use wildcards in order to get less specific results
    39. //      ? used for 1 missing char
    40. //      * used for multiple missing chars
    41. for (String file: dir.list(new WildcardFileFilter("*ample*"))) {  
    42. "Wildcard file found, named: "
    43.         }  
    44.           
    45.           
    46. // PrefixFileFilter 
    47. // We can also use the equivalent of startsWith
    48. // for filtering files.
    49. for (String file: dir.list(new PrefixFileFilter("example"))) {  
    50. "Prefix file found, named: "
    51.         }  
    52.           
    53.           
    54. // SuffixFileFilter
    55. // We can also use the equivalent of endsWith
    56. // for filtering files.
    57. for (String file: dir.list(new SuffixFileFilter(".txt"))) {  
    58. "Suffix file found, named: "
    59.         }  
    60.           
    61.           
    62. // OrFileFilter 
    63. // We can use some filters of filters.
    64. // in this case, we use a filter to apply a logical 
    65. // or between our filters.
    66. for (String file: dir.list(new
    67. new WildcardFileFilter("*ample*"), new SuffixFileFilter(".txt")))) {  
    68. "Or file found, named: "
    69.         }  
    70.           
    71. // And this can become very detailed.
    72. // Eg, get all the files that have "ample" in their name
    73. // but they are not text files (so they have no ".txt" extension.
    74. for (String file: dir.list(new AndFileFilter( // we will match 2 filters...
    75. new WildcardFileFilter("*ample*"), // ...the 1st is a wildcard...
    76. new NotFileFilter(new SuffixFileFilter(".txt"))))) { // ...and the 2nd is NOT .txt.
    77. "And/Not file found, named: "
    78.         }  
    79.     }  
    80. }


          可以看清晰看到,使用过滤器,可以分别在指定的目录下,寻找符合条件 

    的文件,比如以什么开头的文件名,支持通配符,甚至支持多个过滤器进行或的操作! 

      输出如下: 

     

    Java代码  

    1. File Filter example...  
    2. File found, named: example  
    3. File found, named: exampleTxt.txt  
    4. Wildcard file found, named: example  
    5. Wildcard file found, named: exampleFileEntry.txt  
    6. Wildcard file found, named: exampleTxt.txt  
    7. Prefix file found, named: example  
    8. Prefix file found, named: exampleFileEntry.txt  
    9. Prefix file found, named: exampleTxt.txt  
    10. Suffix file found, named: exampleFileEntry.txt  
    11. Suffix file found, named: exampleTxt.txt  
    12. Or file found, named: example  
    13. Or file found, named: exampleFileEntry.txt  
    14. Or file found, named: exampleTxt.txt  
    15. And/Not file found, named: example




    四  Comparators比较器 

       org.apache.commons.io.comparator包下的工具类,可以方便进行文件的比较: 

    Java代码  

    1. import
    2. import
    3.   
    4. import
    5. import
    6. import
    7. import
    8. import
    9.   
    10. public final class
    11.       
    12. private static final
    13. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder";  
    14.       
    15. private static final
    16. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\example";  
    17.       
    18. private static final
    19. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\exampleTxt.txt";  
    20.       
    21. public static void
    22. "Comparator example...");  
    23.           
    24. //NameFileComparator
    25.           
    26. // Let's get a directory as a File object
    27. // and sort all its files.
    28.         File parentDir = FileUtils.getFile(PARENT_DIR);  
    29. new
    30.         File[] sortedFiles = comparator.sort(parentDir.listFiles());  
    31.           
    32. "Sorted by name files in parent directory: ");  
    33. for
    34. "\t"+ file.getAbsolutePath());  
    35.         }  
    36.           
    37.           
    38. // SizeFileComparator
    39.           
    40. // We can compare files based on their size.
    41. // The boolean in the constructor is about the directories.
    42. //      true: directory's contents count to the size.
    43. //      false: directory is considered zero size.
    44. new SizeFileComparator(true);  
    45.         File[] sizeFiles = sizeComparator.sort(parentDir.listFiles());  
    46.           
    47. "Sorted by size files in parent directory: ");  
    48. for
    49. "\t"+ file.getName() + " with size (kb): "
    50.         }  
    51.           
    52.           
    53. // LastModifiedFileComparator
    54.           
    55. // We can use this class to find which file was more recently modified.
    56. new
    57.         File[] lastModifiedFiles = lastModified.sort(parentDir.listFiles());  
    58.           
    59. "Sorted by last modified files in parent directory: ");  
    60. for
    61. new
    62. "\t"+ file.getName() + " last modified on: "
    63.         }  
    64.           
    65. // Or, we can also compare 2 specific files and find which one was last modified.
    66. //      returns > 0 if the first file was last modified.
    67. //      returns  0)
    68. "File " + file1.getName() + " was modified last because...");  
    69. else
    70. "File " + file2.getName() + "was modified last because...");  
    71.           
    72. "\t"+ file1.getName() + " last modified on: "
    73. new
    74. "\t"+ file2.getName() + " last modified on: "
    75. new
    76.     }  
    77. }



       输出如下: 

    Java代码  

      1. Comparator example...  
      2. Sorted by name files in parent directory:   
      3.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\comparator1.txt  
      4.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\comperator2.txt  
      5.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\example  
      6.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleFileEntry.txt  
      7.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleTxt.txt  
      8. Sorted by size files in parent directory:   
      9. 0
      10. 87
      11. 503
      12. 1458
      13. 4436
      14. Sorted by last modified files in parent directory:   
      15. 26 14:02:22 EET 2014
      16. 26 23:42:55 EET 2014
      17. 28 14:48:28 EET 2014
      18. 28 14:48:52 EET 2014
      19. 28 14:53:50 EET 2014
      20. File example was modified last because...  
      21. 26 23:42:55 EET 2014
      22. 26 14:02:22 EET 2014



          可以看到,在上面的代码中 

      NameFileComparator: 文件名的比较器,可以进行文件名称排序; 

      SizeFileComparator: 按照文件大小比较 

      LastModifiedFileComparator: 根据最新修改日期比较 


      五  input包 

          在 common io的org.apache.commons.io.input 包中,有各种对InputStream的实现类: 

      我们看下其中的TeeInputStream, ,它接受InputStream和Outputstream参数,例子如下: 

        

      Java代码  

      1. import
      2. import
      3. import
      4. import
      5.   
      6. import
      7. import
      8. import
      9.   
      10.   
      11. public final class
      12.       
      13. private static final
      14. "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\InputOutputExampleFolder\\web.xml";  
      15.       
      16. private static final String INPUT = "This should go to the output.";  
      17.   
      18. public static void
      19. "Input example...");  
      20. null;  
      21. null;  
      22.           
      23. try
      24.               
      25. // XmlStreamReader
      26.               
      27. // We can read an xml file and get its encoding.
      28.             File xml = FileUtils.getFile(XML_PATH);  
      29.               
      30. new
      31. "XML encoding: "
      32.               
      33.               
      34. // TeeInputStream
      35.               
      36. // This very useful class copies an input stream to an output stream
      37. // and closes both using only one close() method (by defining the 3rd
      38. // constructor parameter as true).
      39. new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));  
      40. new
      41.               
      42. new TeeInputStream(in, out, true);  
      43. new byte[INPUT.length()]);  
      44.   
      45. "Output stream: "
      46. catch
      47.             e.printStackTrace();  
      48. finally
      49. try
      50. catch
      51.               
      52. try
      53. catch
      54.         }  
      55.     }  
      56. }



      输出: 

        

      Java代码  

      1. Input example...  
      2. XML encoding: UTF-8
      3. Output stream: This should go to the output.


         tee = new TeeInputStream(in, out, true); 

         中,分别三个参数,将输入流的内容输出到输出流,true参数为最后关闭流 

      六 output工具类包 

        

        其中的org.apache.commons.io.output 是实现了outputstream,其中好特别的是 

      TeeOutputStream能将一个输入流分别输出到两个输出流 

        

      Java代码  

      1. import
      2. import
      3. import
      4.   
      5. import
      6. import
      7.   
      8. public final class
      9.       
      10. private static final String INPUT = "This should go to the output.";  
      11.   
      12. public static void
      13. "Output example...");  
      14. null;  
      15. null;  
      16.           
      17. try
      18.               
      19. // TeeOutputStream
      20.               
      21. new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));  
      22. new
      23. new
      24.               
      25. new
      26. new TeeInputStream(in, teeOut, true);  
      27. new byte[INPUT.length()]);  
      28.   
      29. "Output stream 1: "
      30. "Output stream 2: "
      31.               
      32. catch
      33.             e.printStackTrace();  
      34. finally
      35. // No need to close teeOut. When teeIn closes, it will also close its
      36. // Output stream (which is teeOut), which will in turn close the 2
      37. // branches (out1, out2).
      38. try
      39. catch
      40.         }  
      41.     }  
      42. }



        输出: 

      Java代码  

        1. Output example...  
        2. Output stream 1: This should go to the output.  
        3. Output stream 2: This should go to the output.