Java IO 系统.docx

上传人:b****7 文档编号:9665884 上传时间:2023-02-05 格式:DOCX 页数:24 大小:36.75KB
下载 相关 举报
Java IO 系统.docx_第1页
第1页 / 共24页
Java IO 系统.docx_第2页
第2页 / 共24页
Java IO 系统.docx_第3页
第3页 / 共24页
Java IO 系统.docx_第4页
第4页 / 共24页
Java IO 系统.docx_第5页
第5页 / 共24页
点击查看更多>>
下载资源
资源描述

Java IO 系统.docx

《Java IO 系统.docx》由会员分享,可在线阅读,更多相关《Java IO 系统.docx(24页珍藏版)》请在冰豆网上搜索。

Java IO 系统.docx

JavaIO系统

9.4翻译

TheJavaI/OSystem

Creatingagoodinput/output(I/O)systemisoneofthemoredifficulttasksforthelanguagedesigner.

Thisisevidencedbythenumberofdifferentapproaches.Thechallengeseemstobeincoveringalleventualities.NotonlyaretheredifferentsourcesandsinksofI/Othatyouwanttocommunicatewith(files,theconsole,networkconnections,etc.),butyouneedtotalktotheminawidevarietyofways(sequential,random-SQLServer2000,buffered,binary,character,bylines,bywords,etc.).

TheJavalibrarydesignersattackedthisproblembycreatinglotsofclasses.Infact,therearesomanyclassesforJava’sI/Osystemthatitcanbeintimidatingatfirst(ironically,theJavaI/Odesignactuallypreventsanexplosionofclasses).TherewasalsoasignificantchangeintheI/OlibraryafterJava1.0,whentheoriginalbyte-orientedlibrarywassupplementedwithchar-oriented,Unicode-basedI/Oclasses.InJDK1.4,thenioclasses(for“newI/O,”anamewe’llstillbeusingyearsfromnow)wereaddedforimprovedperformanceandfunctionality.Asaresult,thereareafairnumberofclassestolearnbeforeyouunderstandenoughofJava’sI/Opicturethatyoucanuseitproperly.Inaddition,it’sratherimportanttounderstandtheevolutionhistoryoftheI/Olibrary,evenifyourfirstreactionis“don’tbothermewithhistory,justshowmehowtouseit!

”Theproblemisthatwithoutthehistoricalperspective,youwillrapidlybecomeconfusedwithsomeoftheclassesandwhenyoushouldandshouldn’tusethem.

ThischapterwillgiveyouanintroductiontothevarietyofI/OclassesinthestandardJavalibraryandhowtousethem.

TheFileclass

Beforegettingintotheclassesthatactuallyreadandwritedatatostreams,we’lllookatautilityprovidedwiththelibrarytoassistyouinhandlingfiledirectoryissues.

TheFileclasshasadeceivingname;youmightthinkitreferstoafile,butitdoesn’t.Itcanrepresenteitherthenameofaparticularfileorthenamesofasetoffilesinadirectory.Ifit’sasetoffiles,youcanaskforthatsetusingthelist( )method,whichreturnsanarrayofString.Itmakessensetoreturnanarrayratherthanoneoftheflexiblecontainerclasses,becausethenumberofelementsisfixed,andifyouwantadifferentdirectorylisting,youjustcreateadifferentFileobject.Infact,“FilePath”wouldhavebeenabetternamefortheclass.Thissectionshowsanexampleoftheuseofthisclass,includingtheassociatedFilenameFilterinterface.

Adirectorylister

Supposeyou’dliketoseeadirectorylisting.TheFileobjectcanbelistedintwoways.Ifyoucalllist( )withnoarguments,you’llgetthefulllistthattheFileobjectcontains.However,ifyouwantarestrictedlist—forexample,ifyouwantallofthefileswithanextensionof.java—thenyouusea“directoryfilter,”whichisaclassthattellshowtoselecttheFileobjectsfordisplay.

TheDirFilterclass“implements”theinterfaceFilenameFilter.It’susefultoseehowsimpletheFilenameFilterinterfaceis:

publicinterfaceFilenameFilter{

booleanaccept(Filedir,Stringname);

}

Itsaysallthatthistypeofobjectdoesisprovideamethodcalledaccept( ).Thewholereasonbehindthecreationofthisclassistoprovidetheaccept( )methodtothelist( )methodsothatlist( )can“callback”accept( )todeterminewhichfilenamesshouldbeincludedinthelist.Thus,thisstructureisoftenreferredtoasacallback.Morespecifically,thisisanexampleoftheStrategyPattern,becauselist( )implementsbasicfunctionality,andyouprovidetheStrategyintheformofaFilenameFilterinordertocompletethealgorithmnecessaryforlist( )toprovideitsservice.Becauselist( )takesaFilenameFilterobjectasitsargument,itmeansthatyoucanpassanobjectofanyclassthatimplementsFilenameFiltertochoose(evenatruntime)howthelist( )methodwillbehave.Thepurposeofacallbackistoprovideflexibilityinthebehaviorofcode.

DirFiltershowsthatjustbecauseaninterfacecontainsonlyasetofmethods,you’renotrestrictedtowritingonlythosemethods.(Youmustatleastprovidedefinitionsforallthemethodsinaninterface,however.)Inthiscase,theDirFilterconstructorisalsocreated.

Theaccept( )methodmustacceptaFileobjectrepresentingthedirectorythataparticularfileisfoundin,andaStringcontainingthenameofthatfile.Youmightchoosetouseorignoreeitherofthesearguments,butyouwillprobablyatleastusethefilename.Rememberthatthelist( )methodiscallingaccept( )foreachofthefilenamesinthedirectoryobjecttoseewhichoneshouldbeincluded;thisisindicatedbythebooleanresultreturnedbyaccept( ).

Tomakesuretheelementyou’reworkingwithisonlythefilenameandcontainsnopathinformation,allyouhavetodoistaketheStringobjectandcreateaFileobjectoutofit,thencallgetName( ),whichstripsawayallthepathinformation(inaplatform-independentway).Thenaccept( )usesaregularexpressionmatcherobjecttoseeiftheregularexpressionregexmatchesthenameofthefile.Usingaccept( ),thelist( )methodreturnsanarray.

Inputandoutput

I/Olibrariesoftenusetheabstractionofastream,whichrepresentsanydatasourceorsinkasanobjectcapableofproducingorreceivingpiecesofdata.ThestreamhidesthedetailsofwhathappenstothedatainsidetheactualI/Odevice.

TheJavalibraryclassesforI/Oaredividedbyinputandoutput,asyoucanseebylookingattheclasshierarchyintheJDKdocumentation.Byinheritance,everythingderivedfromtheInputStreamorReaderclasseshavebasicmethodscalledread( )forreadingasinglebyteorarrayofbytes.Likewise,everythingderivedfromOutputStreamorWriterclasseshavebasicmethodscalledwrite( )forwritingasinglebyteorarrayofbytes.However,youwon’tgenerallyusethesemethods;theyexistsothatotherclassescanusethem—theseotherclassesprovideamoreusefulinterface.Thus,you’llrarelycreateyourstreamobjectbyusingasingleclass,butinsteadwilllayermultipleobjectstogethertoprovideyourdesiredfunctionality.ThefactthatyoucreatemorethanoneobjecttocreateasingleresultingstreamistheprimaryreasonthatJava’sstreamlibraryisconfusing.

It’shelpfultocategorizetheclassesbytheirfunctionality.InJava1.0,thelibrarydesignersstartedbydecidingthatallclassesthathadanythingtodowithinputwouldbeinheritedfromInputStream,andallclassesthatwereassociatedwithoutputwouldbeinheritedfromOutputStream.

TypesofInputStream

InputStream’sjobistorepresentclassesthatproduceinputfromdifferentsources.Thesesourcescanbe:

1.Anarrayofbytes.

2.AStringobject.

3.Afile.

4.A“pipe,”whichworkslikeaphysicalpipe:

Youputthingsinatoneendandtheycomeouttheother.

5.Asequenceofotherstreams,soyoucancollectthemtogetherintoasinglestream.

6.Othersources,suchasanInternetconnection.(ThisiscoveredinThinkinginEnterpriseJava.)

EachofthesehasanassociatedsubclassofInputStream.Inaddition,theFilterInputStreamisalsoatypeofInputStream,toprovideabaseclassfor"decorator"classesthatattachattributesorusefulinterfacestoinputstreams.Thisisdiscussedlater.

TypesofOutputStream

Thiscategoryincludestheclassesthatdecidewhereyouroutputwillgo:

anarrayofbytes(noString,however;presumably,youcancreateoneusingthearrayofbytes),afile,ora“pipe.”

Inaddition,theFilterOutputStreamprovidesabaseclassfor"decorator"classesthatattachattributesorusefulinterfacestooutputstreams.

Addingattributesandusefulinterfaces

TheuseoflayeredobjectstodynamicallyandtransparentlyaddresponsibilitiestoindividualobjectsisreferredtoastheDecoratorpattern.(PatternsarethesubjectofThinkinginPatterns(withJava)atwww.BruceE.)Thedecoratorpatternspecifiesthatallobjectsthatwraparoundyourinitialobjecthavethesameinterface.Thismakesthebasicuseofthedecoratorstransparent—yousendthesamemessagetoanobjectwhetherithasbeendecoratedornot.Thisisthereasonfortheexistenceofthe“filter”classesintheJavaI/Olibrary:

Theabstract“filter”classisthebaseclassforallthedecorators.(Adecoratormusthavethesameinterfaceastheobjectitdecorates,butthedecoratorcanalsoextendtheinterface,whichoccursinseveralofthe“filter”classes).

Decoratorsareoftenusedwhensimplesubclassingresultsinalargenumberofclassesinordertosatisfyeverypossiblecombinationthatisneeded—somanyclassesthatitbecomesimpractical.TheJavaI/Olibraryrequiresmanydifferentcombinationsoffeatures,andthisisthejustificationforusingthedecoratorpattern.Thereisadrawbacktothedecoratorpattern,however.Decoratorsgiveyoumuchmoreflexibilitywhileyou’rewritingaprogram(sinceyoucaneasilymixandmatchattributes),buttheyaddcomplexitytoyourcode.ThereasonthattheJavaI/Olibraryisawkwardtouseisthatyoumustcreatemanyclasses—the“core”I/Otypeplusallthedecorators—inordertogetthesingleI/Oobjectthatyouwant.

TheclassesthatprovidethedecoratorinterfacetocontrolaparticularInputStreamorOutputStreamaretheFilterInputStreamandFilterOutputStream,whichdon’thaveveryintuitivenames.FilterInputStreamandFilterOutputStreamarederivedfromthebaseclassesoftheI/Olibrary,InputStreamandOutputStream,whichisthekeyrequirementofthedecorator(sothatitprovidesthecommoninterfacetoalltheobjectsthatarebeingdecorated).

ReadingfromanInputStreamwithFilterInputStream

TheFilterInputStreamclassesaccomplisht

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 党团工作 > 入党转正申请

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1