Java IO 系统.docx
《Java IO 系统.docx》由会员分享,可在线阅读,更多相关《Java IO 系统.docx(24页珍藏版)》请在冰豆网上搜索。
![Java IO 系统.docx](https://file1.bdocx.com/fileroot1/2023-2/5/5e66ae82-7f7d-43d3-a1d7-6ce12f25dbeb/5e66ae82-7f7d-43d3-a1d7-6ce12f25dbeb1.gif)
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