org.apache.commons.io

Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。其中CommonsIO是Apache的一个开源的工具包,封装了IO操作的相关类,使用CommonsIO可以很方便的读写文件、URL代码等。Commons IO是JakartaCommons项目的一个子项目。用来帮助进行IO功能开发.它包含三个主要的领域:
  • Utility classes-提供一些静态方法来完成公共任务.
  • Filters-提供文件过滤器的各种实现.
  • Streams-提供实用的Stream,reader与 writer实现.
项目主页: http://commons.apache.org/io/

官网Commons IO的简介:

Commons IO is a library of utilities to assist with developingIO functionality.

There are six main areas included:

  • Utility classes - with static methods to perform commontasks
  • Input - useful Input Stream and Reader implementations
  • Output - useful Output Stream and Writer implementations
  • Filters - various implementations of file filters
  • Comparators - various implementations ofjava.util.Comparator for files
  • File Monitor - a component for monitoring file systemevents


Packages

org.apache.commons.io

This package defines utility classes for working with streams,readers, writers and files.

org.apache.commons.io.comparator

This package provides variousComparator implementations forFiles.

org.apache.commons.io.filefilter

This package defines an interface (IOFileFilter) that combines bothFileFilter and FilenameFilter.

org.apache.commons.io.input

This package provides implementations of input classes, suchasInputStream and Reader.

org.apache.commons.io.output

This package provides implementations of output classes,such asOutputStream and Writer.


org.apache.commons.io.filefilter
filefilter包中包含了大量的文件过滤器,这些过滤器都继承或实现了java.io.FileFilter和java.io.FilenameFilter两个接口,如:HiddenFileFilter、SizeFileFilter,实现了对文件或目录的过滤。
例如,显示当前目录下的所有隐藏文件:

     File dir = new File(".");

     
String[] files = dir.list( HiddenFileFilter.HIDDEN );
 

     
for ( int i = 0; i < files.length; i++ ) 

     
{

       
  System.out.println(files[i]);
 

     
}
 


类图
Apache <wbr>Commons <wbr>IO <wbr>(二) <wbr>- <wbr>FileFilter



过滤器 

                              功能
TrueFileFilter            不进行过滤
FalseFileFilter          过滤所有文件及目录

FileFileFilter            仅接受文件
DirectoryFilter        仅接受目录

PrefixFileFilter        基于前缀(不带路径的文件名)
SuffixFileFilter        基于后缀(不带路径的文件名)
NameFileFilter            基于文件名称(不带路径的文件名)
WildcardFileFilter    基于通配符(不带路径的文件名)
RegexFileFilter          基于正则表达式
AgeFileFilter              基于最后修改时间
SizeFileFilter            基于文件尺寸
MagicNumberFileFileter 基于Magic Number
EmptyFileFilter          基于文件或目录是否为空
HiddenFileFilter        基于文件或目录是否隐藏

CanReadFileFilter      基于是否可读
CanWriteFileFilter    基于是否可写入

DelegateFileFilter    将普通的FileFilter和FilenameFilter包装成IOFileFilter


复合过滤器                        功能
AndFileFilter              基于AND逻辑运算
OrFileFilter                基于OR逻辑运算
NotFileFilter              基于NOT逻辑运算


工具类:FileFilterUtils         
  • 提供一些工厂方法用于生成各类文件过滤器
  • 提供一些静态方法用于对指定的File集合进行过滤
  1. package simple.io;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.MalformedURLException;
  8. import java.net.URL;
  9. import java.util.List;
  10. import org.apache.commons.io.FileSystemUtils;
  11. import org.apache.commons.io.FileUtils;
  12. import org.apache.commons.io.FilenameUtils;
  13. import org.apache.commons.io.IOUtils;
  14. import org.apache.commons.io.LineIterator;
  15. import org.apache.commons.io.filefilter.AndFileFilter;
  16. import org.apache.commons.io.filefilter.DirectoryFileFilter;
  17. import org.apache.commons.io.filefilter.FileFilterUtils;
  18. import org.apache.commons.io.filefilter.NotFileFilter;
  19. import org.apache.commons.io.filefilter.OrFileFilter;
  20. import org.apache.commons.io.filefilter.PrefixFileFilter;
  21. import org.apache.commons.io.filefilter.SuffixFileFilter;
  22. import org.junit.Test;
  23. public class ApacheIO {
  24. /**
  25. * 用普通的Java IO来解析HTML <br>
  26. */
  27. @Test
  28. public void testReadURL1() throws MalformedURLException, IOException{
  29. InputStream in = new URL( "http://www.blogjava.net/rongxh7" ).openStream();
  30. try {
  31. InputStreamReader inR = new InputStreamReader( in );
  32. BufferedReader buf = new BufferedReader( inR );
  33. String line;
  34. while ( ( line = buf.readLine() ) != null ) {
  35. System.out.println( line );
  36. }
  37. } finally {
  38. in.close();
  39. }
  40. }
  41. /**
  42. * 用Apache IO来解析HTML <br>
  43. * 学习要点: <br>
  44. * IOUtils contains utility methods dealing with reading, writing and copying. <br>
  45. * The methods work on InputStream, OutputStream, Reader and Writer.
  46. */
  47. @Test
  48. public void testReadURL2() throws MalformedURLException, IOException {
  49. InputStream in = new URL("http://www.blogjava.net/rongxh7").openStream();
  50. try {
  51. System.out.println(IOUtils.toString(in));
  52. } finally {
  53. IOUtils.closeQuietly(in);
  54. }
  55. }
  56. /**
  57. * 用Apache IO来读文件<br>
  58. * 学习要点:<br>
  59. * The FileUtils class contains utility methods for working with File objects.<br>
  60. * These include reading, writing, copying and comparing files.
  61. */
  62. @Test
  63. public void testReadFile() throws IOException {
  64. File file = new File("README");
  65. List<String> lines = FileUtils.readLines(file, "GBK");
  66. for(String line : lines){
  67. System.out.println(line);
  68. }
  69. }
  70. /**
  71. * 用Apache IO来操作文件名
  72. * The FilenameUtils class contains utility methods <br>
  73. * for working with filenames without using File objects.
  74. */
  75. @Test
  76. public void testFileName() {
  77. String filename = "C:/a/b/ccc.txt";
  78. String baseName = FilenameUtils.getBaseName(filename); //ccc
  79. String extName = FilenameUtils.getExtension(filename); //txt
  80. String fullPath = FilenameUtils.getFullPath(filename); //C:/a/b
  81. String name = FilenameUtils.getName(filename); //ccc.txt
  82. System.out.println(baseName);
  83. System.out.println(extName);
  84. System.out.println(fullPath);
  85. System.out.println(name);
  86. }
  87. /**
  88. * 用Apache IO查询磁盘空间
  89. * The FileSystemUtils class contains utility methods <br>
  90. * for working with the file system to access functionality not supported by the JDK.
  91. */
  92. @Test
  93. public void testFindDrive() throws IOException{
  94. long space = FileSystemUtils.freeSpaceKb("C:/"); //查C盘还剩下多少可用空间
  95. System.out.println("C盘可用空间为: " + space/1024 + " MB");
  96. }
  97. /**
  98. * Line Iterator的用法 <br>
  99. * The org.apache.commons.io.LineIterator class provides a flexible way <br>
  100. * for working with a line-based file. An instance can be created directly, <br>
  101. * or via factory methods on FileUtils or IOUtils.
  102. */
  103. @Test
  104. public void testLineIterater() throws IOException{
  105. File file = new File("README");
  106. LineIterator it = FileUtils.lineIterator(file, "GBK");
  107. try{
  108. while(it.hasNext()){
  109. String line = it.nextLine();
  110. System.out.println(line);
  111. }
  112. } finally {
  113. LineIterator.closeQuietly(it);
  114. }
  115. }
  116. /**
  117. *
  118. * 各种常用的FileFiter
  119. *
  120. * There are a number of 'primitive' filters:
  121. *
  122. * DirectoryFilter Only accept directories
  123. * PrefixFileFilter Filter based on a prefix
  124. * SuffixFileFilter Filter based on a suffix
  125. * NameFileFilter Filter based on a filename
  126. * WildcardFileFilter Filter based on wildcards
  127. * AgeFileFilter Filter based on last modified time of file
  128. * SizeFileFilter Filter based on file size
  129. *
  130. * And there are five 'boolean' filters:
  131. *
  132. * TrueFileFilter Accept all files
  133. * FalseFileFilter Accept no files
  134. * NotFileFilter Applies a logical NOT to an existing filter
  135. * AndFileFilter Combines two filters using a logical AND
  136. * OrFileFilter Combines two filter using a logical OR
  137. *
  138. */
  139. /**
  140. * FileFilter的用法1
  141. * 用 "new 子类" 的方式
  142. *
  143. */
  144. @Test
  145. public void testFileFilter1(){
  146. File dir = new File("data"); //若表示本目录,则用"."
  147. //Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
  148. String[] files = dir.list(
  149. //Constructs a new file filter that ANDs the result of two other filters.
  150. new AndFileFilter(
  151. new AndFileFilter(
  152. new PrefixFileFilter("t"), //Constructs a new Prefix file filter for a single prefix.
  153. new OrFileFilter( //Constructs a new file filter that ORs the result of two other filters.
  154. new SuffixFileFilter(".txt"), //Constructs a new Suffix file filter for a single extension.
  155. new SuffixFileFilter(".dic")
  156. )
  157. ),
  158. //Constructs a new file filter that NOTs the result of another filters.
  159. new NotFileFilter(
  160. DirectoryFileFilter.INSTANCE //This filter accepts Files that are directories.
  161. )
  162. )
  163. );
  164. for ( int i=0; i<files.length; i++ ) {
  165. System.out.println(files[i]);
  166. }
  167. }
  168. /**
  169. * FileFilter的用法2
  170. * 用FileFilterUtils的方式
  171. */
  172. @Test
  173. public void testFileFilter2(){
  174. File dir = new File("data");
  175. String[] files = dir.list(
  176. FileFilterUtils.andFileFilter(
  177. FileFilterUtils.andFileFilter(
  178. FileFilterUtils.prefixFileFilter("t"),
  179. FileFilterUtils.orFileFilter(
  180. FileFilterUtils.suffixFileFilter(".txt"),
  181. FileFilterUtils.suffixFileFilter(".dic")
  182. )
  183. ),
  184. FileFilterUtils.notFileFilter(
  185. FileFilterUtils.directoryFileFilter()
  186. )
  187. )
  188. );
  189. for ( int i=0; i<files.length; i++ ) {
  190. System.out.println(files[i]);
  191. }
  192. }
  193. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值