当前位置:首页 > > 充电吧
[导读]Apache Commons IO 包绝对是好东西,地址在http://commons.apache.org/proper/commons-io/,下面用例子分别介绍: 1) 工具类 2) 输入

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.





本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除。
换一批
延伸阅读

LED驱动电源的输入包括高压工频交流(即市电)、低压直流、高压直流、低压高频交流(如电子变压器的输出)等。

关键字: 驱动电源

在工业自动化蓬勃发展的当下,工业电机作为核心动力设备,其驱动电源的性能直接关系到整个系统的稳定性和可靠性。其中,反电动势抑制与过流保护是驱动电源设计中至关重要的两个环节,集成化方案的设计成为提升电机驱动性能的关键。

关键字: 工业电机 驱动电源

LED 驱动电源作为 LED 照明系统的 “心脏”,其稳定性直接决定了整个照明设备的使用寿命。然而,在实际应用中,LED 驱动电源易损坏的问题却十分常见,不仅增加了维护成本,还影响了用户体验。要解决这一问题,需从设计、生...

关键字: 驱动电源 照明系统 散热

根据LED驱动电源的公式,电感内电流波动大小和电感值成反比,输出纹波和输出电容值成反比。所以加大电感值和输出电容值可以减小纹波。

关键字: LED 设计 驱动电源

电动汽车(EV)作为新能源汽车的重要代表,正逐渐成为全球汽车产业的重要发展方向。电动汽车的核心技术之一是电机驱动控制系统,而绝缘栅双极型晶体管(IGBT)作为电机驱动系统中的关键元件,其性能直接影响到电动汽车的动力性能和...

关键字: 电动汽车 新能源 驱动电源

在现代城市建设中,街道及停车场照明作为基础设施的重要组成部分,其质量和效率直接关系到城市的公共安全、居民生活质量和能源利用效率。随着科技的进步,高亮度白光发光二极管(LED)因其独特的优势逐渐取代传统光源,成为大功率区域...

关键字: 发光二极管 驱动电源 LED

LED通用照明设计工程师会遇到许多挑战,如功率密度、功率因数校正(PFC)、空间受限和可靠性等。

关键字: LED 驱动电源 功率因数校正

在LED照明技术日益普及的今天,LED驱动电源的电磁干扰(EMI)问题成为了一个不可忽视的挑战。电磁干扰不仅会影响LED灯具的正常工作,还可能对周围电子设备造成不利影响,甚至引发系统故障。因此,采取有效的硬件措施来解决L...

关键字: LED照明技术 电磁干扰 驱动电源

开关电源具有效率高的特性,而且开关电源的变压器体积比串联稳压型电源的要小得多,电源电路比较整洁,整机重量也有所下降,所以,现在的LED驱动电源

关键字: LED 驱动电源 开关电源

LED驱动电源是把电源供应转换为特定的电压电流以驱动LED发光的电压转换器,通常情况下:LED驱动电源的输入包括高压工频交流(即市电)、低压直流、高压直流、低压高频交流(如电子变压器的输出)等。

关键字: LED 隧道灯 驱动电源
关闭