快速入门apache commons io包
扫描二维码
随时随地手机看文章
Apache Commons IO 包绝对是好东西,地址在http://commons.apache.org/proper/commons-io/,下面用例子分别介绍:
1) 工具类
2) 输入
3) 输出
4) filters过滤
5) Comparators
6) 文件监控
总的入口例子为:
Java代码publicclassApacheCommonsExampleMain{
publicstaticvoidmain(String[]args){
UtilityExample.runExample();
FileMonitorExample.runExample();
FiltersExample.runExample();
InputExample.runExample();
OutputExample.runExample();
ComparatorExample.runExample();
}
}
一 工具类包UtilityExample代码:
这个工具类包分如下几个主要工具类:
1) FilenameUtils:主要处理各种操作系统下对文件名的操作
2) FileUtils:处理文件的打开,移动,读取和判断文件是否存在
3) IOCASE:字符串的比较
4) FileSystemUtils:返回磁盘的空间大小
Java代码importjava.io.File;
importjava.io.IOException;
importorg.apache.commons.io.FileSystemUtils;
importorg.apache.commons.io.FileUtils;
importorg.apache.commons.io.FilenameUtils;
importorg.apache.commons.io.LineIterator;
importorg.apache.commons.io.IOCase;
publicfinalclassUtilityExample{
//WeareusingthefileexampleTxt.txtinthefolderExampleFolder,
//andweneedtoprovidethefullpathtotheUtilityclasses.
privatestaticfinalStringEXAMPLE_TXT_PATH=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleTxt.txt";
privatestaticfinalStringPARENT_DIR=
"C:\Users\Lilykos\workspace\ApacheCommonsExample";
publicstaticvoidrunExample()throwsIOException{
System.out.println("UtilityClassesexample...");
//FilenameUtils
System.out.println("FullpathofexampleTxt:"+
FilenameUtils.getFullPath(EXAMPLE_TXT_PATH));
System.out.println("FullnameofexampleTxt:"+
FilenameUtils.getName(EXAMPLE_TXT_PATH));
System.out.println("ExtensionofexampleTxt:"+
FilenameUtils.getExtension(EXAMPLE_TXT_PATH));
System.out.println("BasenameofexampleTxt:"+
FilenameUtils.getBaseName(EXAMPLE_TXT_PATH));
//FileUtils
//WecancreateanewFileobjectusingFileUtils.getFile(String)
//andthenusethisobjecttogetinformationfromthefile.
FileexampleFile=FileUtils.getFile(EXAMPLE_TXT_PATH);
LineIteratoriter=FileUtils.lineIterator(exampleFile);
System.out.println("ContentsofexampleTxt...");
while(iter.hasNext()){
System.out.println("t"+iter.next());
}
iter.close();
//Wecancheckifafileexistssomewhereinsideacertaindirectory.
Fileparent=FileUtils.getFile(PARENT_DIR);
System.out.println("ParentdirectorycontainsexampleTxtfile:"+
FileUtils.directoryContains(parent,exampleFile));
//IOCase
Stringstr1="ThisisanewString.";
Stringstr2="ThisisanothernewString,yes!";
System.out.println("Endswithstring(casesensitive):"+
IOCase.SENSITIVE.checkEndsWith(str1,"string."));
System.out.println("Endswithstring(caseinsensitive):"+
IOCase.INSENSITIVE.checkEndsWith(str1,"string."));
System.out.println("Stringequality:"+
IOCase.SENSITIVE.checkEquals(str1,str2));
//FileSystemUtils
System.out.println("Freediskspace(inKB):"+FileSystemUtils.freeSpaceKb("C:"));
System.out.println("Freediskspace(inMB):"+FileSystemUtils.freeSpaceKb("C:")/1024);
}
}
输出:
Java代码UtilityClassesexample...
FullpathofexampleTxt:C:UsersLilykosworkspaceApacheCommonsExampleExampleFolder
FullnameofexampleTxt:exampleTxt.txt
ExtensionofexampleTxt:txt
BasenameofexampleTxt:exampleTxt
ContentsofexampleTxt...
Thisisanexampletextfile.
WewilluseitforexperimentingwithApacheCommonsIO.
ParentdirectorycontainsexampleTxtfile:true
Endswithstring(casesensitive):false
Endswithstring(caseinsensitive):true
Stringequality:false
Freediskspace(inKB):32149292
Freediskspace(inMB):31395
二 FileMonitor工具类包
这个org.apache.commons.io.monitor 包中的工具类可以监视文件或者目录的变化,获得指定文件或者目录的相关信息,下面看例子:
Java代码importjava.io.File;
importjava.io.IOException;
importorg.apache.commons.io.FileDeleteStrategy;
importorg.apache.commons.io.FileUtils;
importorg.apache.commons.io.monitor.FileAlterationListenerAdaptor;
importorg.apache.commons.io.monitor.FileAlterationMonitor;
importorg.apache.commons.io.monitor.FileAlterationObserver;
importorg.apache.commons.io.monitor.FileEntry;
publicfinalclassFileMonitorExample{
privatestaticfinalStringEXAMPLE_PATH=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleFileEntry.txt";
privatestaticfinalStringPARENT_DIR=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder";
privatestaticfinalStringNEW_DIR=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\newDir";
privatestaticfinalStringNEW_FILE=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\newFile.txt";
publicstaticvoidrunExample(){
System.out.println("FileMonitorexample...");
//FileEntry
//Wecanmonitorchangesandgetinformationaboutfiles
//usingthemethodsofthisclass.
FileEntryentry=newFileEntry(FileUtils.getFile(EXAMPLE_PATH));
System.out.println("Filemonitored:"+entry.getFile());
System.out.println("Filename:"+entry.getName());
System.out.println("Isthefileadirectory?:"+entry.isDirectory());
//FileMonitoring
//Createanewobserverforthefolderandaddalistener
//thatwillhandletheeventsinaspecificdirectoryandtakeaction.
FileparentDir=FileUtils.getFile(PARENT_DIR);
FileAlterationObserverobserver=newFileAlterationObserver(parentDir);
observer.addListener(newFileAlterationListenerAdaptor(){
@Override
publicvoidonFileCreate(Filefile){
System.out.println("Filecreated:"+file.getName());
}
@Override
publicvoidonFileDelete(Filefile){
System.out.println("Filedeleted:"+file.getName());
}
@Override
publicvoidonDirectoryCreate(Filedir){
System.out.println("Directorycreated:"+dir.getName());
}
@Override
publicvoidonDirectoryDelete(Filedir){
System.out.println("Directorydeleted:"+dir.getName());
}
});
//Addamoniorthatwillcheckforeventseveryxms,
//andattachallthedifferentobserversthatwewant.
FileAlterationMonitormonitor=newFileAlterationMonitor(500,observer);
try{
monitor.start();
//Afterweattachedthemonitor,wecancreatesomefilesanddirectories
//andseewhathappens!
FilenewDir=newFile(NEW_DIR);
FilenewFile=newFile(NEW_FILE);
newDir.mkdirs();
newFile.createNewFile();
Thread.sleep(1000);
FileDeleteStrategy.NORMAL.delete(newDir);
FileDeleteStrategy.NORMAL.delete(newFile);
Thread.sleep(1000);
monitor.stop();
}catch(IOExceptione){
e.printStackTrace();
}catch(InterruptedExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
}
}
输出如下:
Java代码FileMonitorexample...
Filemonitored:C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexampleFileEntry.txt
Filename:exampleFileEntry.txt
Isthefileadirectory?:false
Directorycreated:newDir
Filecreated:newFile.txt
Directorydeleted:newDir
Filedeleted: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代码importjava.io.File;
importorg.apache.commons.io.FileUtils;
importorg.apache.commons.io.IOCase;
importorg.apache.commons.io.filefilter.AndFileFilter;
importorg.apache.commons.io.filefilter.NameFileFilter;
importorg.apache.commons.io.filefilter.NotFileFilter;
importorg.apache.commons.io.filefilter.OrFileFilter;
importorg.apache.commons.io.filefilter.PrefixFileFilter;
importorg.apache.commons.io.filefilter.SuffixFileFilter;
importorg.apache.commons.io.filefilter.WildcardFileFilter;
publicfinalclassFiltersExample{
privatestaticfinalStringPARENT_DIR=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder";
publicstaticvoidrunExample(){
System.out.println("FileFilterexample...");
//NameFileFilter
//Rightnow,intheparentdirectorywehave3files:
//directoryexample
//fileexampleEntry.txt
//fileexampleTxt.txt
//Getallthefilesinthespecifieddirectory
//thatarenamed"example".
Filedir=FileUtils.getFile(PARENT_DIR);
String[]acceptedNames={"example","exampleTxt.txt"};
for(Stringfile:dir.list(newNameFileFilter(acceptedNames,IOCase.INSENSITIVE))){
System.out.println("Filefound,named:"+file);
}
//WildcardFileFilter
//Wecanusewildcardsinordertogetlessspecificresults
//?usedfor1missingchar
//*usedformultiplemissingchars
for(Stringfile:dir.list(newWildcardFileFilter("*ample*"))){
System.out.println("Wildcardfilefound,named:"+file);
}
//PrefixFileFilter
//WecanalsousetheequivalentofstartsWith
//forfilteringfiles.
for(Stringfile:dir.list(newPrefixFileFilter("example"))){
System.out.println("Prefixfilefound,named:"+file);
}
//SuffixFileFilter
//WecanalsousetheequivalentofendsWith
//forfilteringfiles.
for(Stringfile:dir.list(newSuffixFileFilter(".txt"))){
System.out.println("Suffixfilefound,named:"+file);
}
//OrFileFilter
//Wecanusesomefiltersoffilters.
//inthiscase,weuseafiltertoapplyalogical
//orbetweenourfilters.
for(Stringfile:dir.list(newOrFileFilter(
newWildcardFileFilter("*ample*"),newSuffixFileFilter(".txt")))){
System.out.println("Orfilefound,named:"+file);
}
//Andthiscanbecomeverydetailed.
//Eg,getallthefilesthathave"ample"intheirname
//buttheyarenottextfiles(sotheyhaveno".txt"extension.
for(Stringfile:dir.list(newAndFileFilter(//wewillmatch2filters...
newWildcardFileFilter("*ample*"),//...the1stisawildcard...
newNotFileFilter(newSuffixFileFilter(".txt"))))){//...andthe2ndisNOT.txt.
System.out.println("And/Notfilefound,named:"+file);
}
}
}
可以看清晰看到,使用过滤器,可以分别在指定的目录下,寻找符合条件
的文件,比如以什么开头的文件名,支持通配符,甚至支持多个过滤器进行或的操作!
输出如下:
Java代码FileFilterexample...
Filefound,named:example
Filefound,named:exampleTxt.txt
Wildcardfilefound,named:example
Wildcardfilefound,named:exampleFileEntry.txt
Wildcardfilefound,named:exampleTxt.txt
Prefixfilefound,named:example
Prefixfilefound,named:exampleFileEntry.txt
Prefixfilefound,named:exampleTxt.txt
Suffixfilefound,named:exampleFileEntry.txt
Suffixfilefound,named:exampleTxt.txt
Orfilefound,named:example
Orfilefound,named:exampleFileEntry.txt
Orfilefound,named:exampleTxt.txt
And/Notfilefound,named:example
四 Comparators比较器
org.apache.commons.io.comparator包下的工具类,可以方便进行文件的比较:
Java代码importjava.io.File;
importjava.util.Date;
importorg.apache.commons.io.FileUtils;
importorg.apache.commons.io.IOCase;
importorg.apache.commons.io.comparator.LastModifiedFileComparator;
importorg.apache.commons.io.comparator.NameFileComparator;
importorg.apache.commons.io.comparator.SizeFileComparator;
publicfinalclassComparatorExample{
privatestaticfinalStringPARENT_DIR=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder";
privatestaticfinalStringFILE_1=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\example";
privatestaticfinalStringFILE_2=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleTxt.txt";
publicstaticvoidrunExample(){
System.out.println("Comparatorexample...");
//NameFileComparator
//Let'sgetadirectoryasaFileobject
//andsortallitsfiles.
FileparentDir=FileUtils.getFile(PARENT_DIR);
NameFileComparatorcomparator=newNameFileComparator(IOCase.SENSITIVE);
File[]sortedFiles=comparator.sort(parentDir.listFiles());
System.out.println("Sortedbynamefilesinparentdirectory:");
for(Filefile:sortedFiles){
System.out.println("t"+file.getAbsolutePath());
}
//SizeFileComparator
//Wecancomparefilesbasedontheirsize.
//Thebooleanintheconstructorisaboutthedirectories.
//true:directory'scontentscounttothesize.
//false:directoryisconsideredzerosize.
SizeFileComparatorsizeComparator=newSizeFileComparator(true);
File[]sizeFiles=sizeComparator.sort(parentDir.listFiles());
System.out.println("Sortedbysizefilesinparentdirectory:");
for(Filefile:sizeFiles){
System.out.println("t"+file.getName()+"withsize(kb):"+file.length());
}
//LastModifiedFileComparator
//Wecanusethisclasstofindwhichfilewasmorerecentlymodified.
LastModifiedFileComparatorlastModified=newLastModifiedFileComparator();
File[]lastModifiedFiles=lastModified.sort(parentDir.listFiles());
System.out.println("Sortedbylastmodifiedfilesinparentdirectory:");
for(Filefile:lastModifiedFiles){
Datemodified=newDate(file.lastModified());
System.out.println("t"+file.getName()+"lastmodifiedon:"+modified);
}
//Or,wecanalsocompare2specificfilesandfindwhichonewaslastmodified.
//returns>0ifthefirstfilewaslastmodified.
//returns0)
System.out.println("File"+file1.getName()+"wasmodifiedlastbecause...");
else
System.out.println("File"+file2.getName()+"wasmodifiedlastbecause...");
System.out.println("t"+file1.getName()+"lastmodifiedon:"+
newDate(file1.lastModified()));
System.out.println("t"+file2.getName()+"lastmodifiedon:"+
newDate(file2.lastModified()));
}
}
输出如下:
Java代码Comparatorexample...
Sortedbynamefilesinparentdirectory:
C:UsersLilykosworkspaceApacheCommonsExampleExampleFoldercomparator1.txt
C:UsersLilykosworkspaceApacheCommonsExampleExampleFoldercomperator2.txt
C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexample
C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexampleFileEntry.txt
C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexampleTxt.txt
Sortedbysizefilesinparentdirectory:
examplewithsize(kb):0
exampleTxt.txtwithsize(kb):87
exampleFileEntry.txtwithsize(kb):503
comperator2.txtwithsize(kb):1458
comparator1.txtwithsize(kb):4436
Sortedbylastmodifiedfilesinparentdirectory:
exampleTxt.txtlastmodifiedon:SunOct2614:02:22EET2014
examplelastmodifiedon:SunOct2623:42:55EET2014
comparator1.txtlastmodifiedon:TueOct2814:48:28EET2014
comperator2.txtlastmodifiedon:TueOct2814:48:52EET2014
exampleFileEntry.txtlastmodifiedon:TueOct2814:53:50EET2014
Fileexamplewasmodifiedlastbecause...
examplelastmodifiedon:SunOct2623:42:55EET2014
exampleTxt.txtlastmodifiedon:SunOct2614:02:22EET2014
可以看到,在上面的代码中
NameFileComparator: 文件名的比较器,可以进行文件名称排序;
SizeFileComparator: 按照文件大小比较
LastModifiedFileComparator: 根据最新修改日期比较
五 input包
在 common io的org.apache.commons.io.input 包中,有各种对InputStream的实现类:
我们看下其中的TeeInputStream, ,它接受InputStream和Outputstream参数,例子如下:
Java代码importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.IOException;
importorg.apache.commons.io.FileUtils;
importorg.apache.commons.io.input.TeeInputStream;
importorg.apache.commons.io.input.XmlStreamReader;
publicfinalclassInputExample{
privatestaticfinalStringXML_PATH=
"C:\Users\Lilykos\workspace\ApacheCommonsExample\InputOutputExampleFolder\web.xml";
privatestaticfinalStringINPUT="Thisshouldgototheoutput.";
publicstaticvoidrunExample(){
System.out.println("Inputexample...");
XmlStreamReaderxmlReader=null;
TeeInputStreamtee=null;
try{
//XmlStreamReader
//Wecanreadanxmlfileandgetitsencoding.
Filexml=FileUtils.getFile(XML_PATH);
xmlReader=newXmlStreamReader(xml);
System.out.println("XMLencoding:"+xmlReader.getEncoding());
//TeeInputStream
//Thisveryusefulclasscopiesaninputstreamtoanoutputstream
//andclosesbothusingonlyoneclose()method(bydefiningthe3rd
//constructorparameterastrue).
ByteArrayInputStreamin=newByteArrayInputStream(INPUT.getBytes("US-ASCII"));
ByteArrayOutputStreamout=newByteArrayOutputStream();
tee=newTeeInputStream(in,out,true);
tee.read(newbyte[INPUT.length()]);
System.out.println("Outputstream:"+out.toString());
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{xmlReader.close();}
catch(IOExceptione){e.printStackTrace();}
try{tee.close();}
catch(IOExceptione){e.printStackTrace();}
}
}
}
输出:
Java代码Inputexample...
XMLencoding:UTF-8
Outputstream:Thisshouldgototheoutput.
tee = new TeeInputStream(in, out, true);
中,分别三个参数,将输入流的内容输出到输出流,true参数为最后关闭流
六 output工具类包
其中的org.apache.commons.io.output 是实现了outputstream,其中好特别的是
TeeOutputStream能将一个输入流分别输出到两个输出流
Java代码importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.IOException;
importorg.apache.commons.io.input.TeeInputStream;
importorg.apache.commons.io.output.TeeOutputStream;
publicfinalclassOutputExample{
privatestaticfinalStringINPUT="Thisshouldgototheoutput.";
publicstaticvoidrunExample(){
System.out.println("Outputexample...");
TeeInputStreamteeIn=null;
TeeOutputStreamteeOut=null;
try{
//TeeOutputStream
ByteArrayInputStreamin=newByteArrayInputStream(INPUT.getBytes("US-ASCII"));
ByteArrayOutputStreamout1=newByteArrayOutputStream();
ByteArrayOutputStreamout2=newByteArrayOutputStream();
teeOut=newTeeOutputStream(out1,out2);
teeIn=newTeeInputStream(in,teeOut,true);
teeIn.read(newbyte[INPUT.length()]);
System.out.println("Outputstream1:"+out1.toString());
System.out.println("Outputstream2:"+out2.toString());
}catch(IOExceptione){
e.printStackTrace();
}finally{
//NoneedtocloseteeOut.WhenteeIncloses,itwillalsocloseits
//Outputstream(whichisteeOut),whichwillinturnclosethe2
//branches(out1,out2).
try{teeIn.close();}
catch(IOExceptione){e.printStackTrace();}
}
}
}
输出:
Java代码Outputexample...
Outputstream1:Thisshouldgototheoutput.
Outputstream2:Thisshouldgototheoutput.