快速入門apache commons io包
Apache Commons IO 包絕對是好東西,地址在http://commons.apache.org/proper/commons-io/,下面用例子分別介紹:
1) 工具類
2) 輸入
3) 輸出
4) filters過濾
5) Comparators
6) 文件監(jiān)控
總的入口例子為:
Java代碼publicclassApacheCommonsExampleMain{
publicstaticvoidmain(String[]args){
UtilityExample.runExample();
FileMonitorExample.runExample();
FiltersExample.runExample();
InputExample.runExample();
OutputExample.runExample();
ComparatorExample.runExample();
}
}
一 工具類包UtilityExample代碼:
這個工具類包分如下幾個主要工具類:
1) FilenameUtils:主要處理各種操作系統(tǒng)下對文件名的操作
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 包中的工具類可以監(jiān)視文件或者目錄的變化,獲得指定文件或者目錄的相關(guān)信息,下面看例子:
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
上面的特性的確很贊!分析下,這個工具類包下的工具類,可以允許我們創(chuàng)建跟蹤文件或目錄變化的監(jiān)聽句柄,當(dāng)文件目錄等發(fā)生任何變化,都可以用“觀察者”的身份進(jìn)行觀察,
其步驟如下:
1) 創(chuàng)建要監(jiān)聽的文件對象
2) 創(chuàng)建FileAlterationObserver 監(jiān)聽對象,在上面的例子中,
File parentDir = FileUtils.getFile(PARENT_DIR);
FileAlterationObserver observer = new FileAlterationObserver(parentDir);
創(chuàng)建的是監(jiān)視parentDir目錄的變化,
3) 為觀察器創(chuàng)建FileAlterationListenerAdaptor的內(nèi)部匿名類,增加對文件及目錄的增加刪除的監(jiān)聽
4) 創(chuàng)建FileAlterationMonitor監(jiān)聽類,每隔500ms監(jiān)聽目錄下的變化,其中開啟監(jiān)視是用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);
}
}
}
可以看清晰看到,使用過濾器,可以分別在指定的目錄下,尋找符合條件
的文件,比如以什么開頭的文件名,支持通配符,甚至支持多個過濾器進(jìn)行或的操作!
輸出如下:
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包下的工具類,可以方便進(jìn)行文件的比較:
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: 文件名的比較器,可以進(jìn)行文件名稱排序;
SizeFileComparator: 按照文件大小比較
LastModifiedFileComparator: 根據(jù)最新修改日期比較
五 input包
在 common io的org.apache.commons.io.input 包中,有各種對InputStream的實(shí)現(xiàn)類:
我們看下其中的TeeInputStream, ,它接受InputStream和Outputstream參數(shù),例子如下:
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);
中,分別三個參數(shù),將輸入流的內(nèi)容輸出到輸出流,true參數(shù)為最后關(guān)閉流
六 output工具類包
其中的org.apache.commons.io.output 是實(shí)現(xiàn)了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.