外文翻译-Java IO 系统_第1页
外文翻译-Java IO 系统_第2页
外文翻译-Java IO 系统_第3页
外文翻译-Java IO 系统_第4页
外文翻译-Java IO 系统_第5页
已阅读5页,还剩20页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

译文资料TheJavaI/OSystemCreatingagoodinput/output(I/O)systemisoneofthemoredifficulttasksforthelanguagedesigner.Thisisevidencedbythenumberofdifferentapproaches.Thechallengeseemstobeincoveringalleventualities.NotonlyaretheredifferentsourcesandsinksofI/Othatyouwanttocommunicatewith(files,theconsole,networkconnections,etc.),butyouneedtotalktotheminawidevarietyofways(sequential,random-SQLServer2000,buffered,binary,character,bylines,bywords,etc.).TheJavalibrarydesignersattackedthisproblembycreatinglotsofclasses.Infact,therearesomanyclassesforJavasI/Osystemthatitcanbeintimidatingatfirst(ironically,theJavaI/Odesignactuallypreventsanexplosionofclasses).TherewasalsoasignificantchangeintheI/OlibraryafterJava1.0,whentheoriginalbyte-orientedlibrarywassupplementedwithchar-oriented,Unicode-basedI/Oclasses.InJDK1.4,thenioclasses(for“newI/O,”anamewellstillbeusingyearsfromnow)wereaddedforimprovedperformanceandfunctionality.Asaresult,thereareafairnumberofclassestolearnbeforeyouunderstandenoughofJavasI/Opicturethatyoucanuseitproperly.Inaddition,itsratherimportanttounderstandtheevolutionhistoryoftheI/Olibrary,evenifyourfirstreactionis“dontbothermewithhistory,justshowmehowtouseit!”Theproblemisthatwithoutthehistoricalperspective,youwillrapidlybecomeconfusedwithsomeoftheclassesandwhenyoushouldandshouldntusethem.ThischapterwillgiveyouanintroductiontothevarietyofI/OclassesinthestandardJavalibraryandhowtousethem.TheFileclassBeforegettingintotheclassesthatactuallyreadandwritedatatostreams,welllookatautilityprovidedwiththelibrarytoassistyouinhandlingfiledirectoryissues.TheFileclasshasadeceivingname;youmightthinkitreferstoafile,butitdoesnt.Itcanrepresenteitherthenameofaparticularfileorthenamesofasetoffilesinadirectory.Ifitsasetoffiles,youcanaskforthatsetusingthelist()method,whichreturnsanarrayofString.Itmakessensetoreturnanarrayratherthanoneoftheflexiblecontainerclasses,becausethenumberofelementsisfixed,andifyouwantadifferentdirectorylisting,youjustcreateadifferentFileobject.Infact,“FilePath”wouldhavebeenabetternamefortheclass.Thissectionshowsanexampleoftheuseofthisclass,includingtheassociatedFilenameFilterinterface.AdirectorylisterSupposeyoudliketoseeadirectorylisting.TheFileobjectcanbelistedintwoways.Ifyoucalllist()withnoarguments,youllgetthefulllistthattheFileobjectcontains.However,ifyouwantarestrictedlistforexample,ifyouwantallofthefileswithanextensionof.javathenyouusea“directoryfilter,”whichisaclassthattellshowtoselecttheFileobjectsfordisplay.TheDirFilterclass“implements”theinterfaceFilenameFilter.ItsusefultoseehowsimpletheFilenameFilterinterfaceis:publicinterfaceFilenameFilterbooleanaccept(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,yourenotrestrictedtowritingonlythosemethods.(Youmustatleastprovidedefinitionsforallthemethodsinaninterface,however.)Inthiscase,theDirFilterconstructorisalsocreated.Theaccept()methodmustacceptaFileobjectrepresentingthedirectorythataparticularfileisfoundin,andaStringcontainingthenameofthatfile.Youmightchoosetouseorignoreeitherofthesearguments,butyouwillprobablyatleastusethefilename.Rememberthatthelist()methodiscallingaccept()foreachofthefilenamesinthedirectoryobjecttoseewhichoneshouldbeincluded;thisisindicatedbythebooleanresultreturnedbyaccept().Tomakesuretheelementyoureworkingwithisonlythefilenameandcontainsnopathinformation,allyouhavetodoistaketheStringobjectandcreateaFileobjectoutofit,thencallgetName(),whichstripsawayallthepathinformation(inaplatform-independentway).Thenaccept()usesaregularexpressionmatcherobjecttoseeiftheregularexpressionregexmatchesthenameofthefile.Usingaccept(),thelist()methodreturnsanarray.InputandoutputI/Olibrariesoftenusetheabstractionofastream,whichrepresentsanydatasourceorsinkasanobjectcapableofproducingorreceivingpiecesofdata.ThestreamhidesthedetailsofwhathappenstothedatainsidetheactualI/Odevice.TheJavalibraryclassesforI/Oaredividedbyinputandoutput,asyoucanseebylookingattheclasshierarchyintheJDKdocumentation.Byinheritance,everythingderivedfromtheInputStreamorReaderclasseshavebasicmethodscalledread()forreadingasinglebyteorarrayofbytes.Likewise,everythingderivedfromOutputStreamorWriterclasseshavebasicmethodscalledwrite()forwritingasinglebyteorarrayofbytes.However,youwontgenerallyusethesemethods;theyexistsothatotherclassescanusethemtheseotherclassesprovideamoreusefulinterface.Thus,youllrarelycreateyourstreamobjectbyusingasingleclass,butinsteadwilllayermultipleobjectstogethertoprovideyourdesiredfunctionality.ThefactthatyoucreatemorethanoneobjecttocreateasingleresultingstreamistheprimaryreasonthatJavasstreamlibraryisconfusing.Itshelpfultocategorizetheclassesbytheirfunctionality.InJava1.0,thelibrarydesignersstartedbydecidingthatallclassesthathadanythingtodowithinputwouldbeinheritedfromInputStream,andallclassesthatwereassociatedwithoutputwouldbeinheritedfromOutputStream.TypesofInputStreamInputStreamsjobistorepresentclassesthatproduceinputfromdifferentsources.Thesesourcescanbe:1.Anarrayofbytes.2.AStringobject.3.Afile.4.A“pipe,”whichworkslikeaphysicalpipe:Youputthingsinatoneendandtheycomeouttheother.5.Asequenceofotherstreams,soyoucancollectthemtogetherintoasinglestream.6.Othersources,suchasanInternetconnection.(ThisiscoveredinThinkinginEnterpriseJava.)EachofthesehasanassociatedsubclassofInputStream.Inaddition,theFilterInputStreamisalsoatypeofInputStream,toprovideabaseclassfordecoratorclassesthatattachattributesorusefulinterfacestoinputstreams.Thisisdiscussedlater.TypesofOutputStreamThiscategoryincludestheclassesthatdecidewhereyouroutputwillgo:anarrayofbytes(noString,however;presumably,youcancreateoneusingthearrayofbytes),afile,ora“pipe.”Inaddition,theFilterOutputStreamprovidesabaseclassfordecoratorclassesthatattachattributesorusefulinterfacestooutputstreams.AddingattributesandusefulinterfacesTheuseoflayeredobjectstodynamicallyandtransparentlyaddresponsibilitiestoindividualobjectsisreferredtoastheDecoratorpattern.(PatternsarethesubjectofThinkinginPatterns(withJava)atwww.BruceE.)Thedecoratorpatternspecifiesthatallobjectsthatwraparoundyourinitialobjecthavethesameinterface.Thismakesthebasicuseofthedecoratorstransparentyousendthesamemessagetoanobjectwhetherithasbeendecoratedornot.Thisisthereasonfortheexistenceofthe“filter”classesintheJavaI/Olibrary:Theabstract“filter”classisthebaseclassforallthedecorators.(Adecoratormusthavethesameinterfaceastheobjectitdecorates,butthedecoratorcanalsoextendtheinterface,whichoccursinseveralofthe“filter”classes).Decoratorsareoftenusedwhensimplesubclassingresultsinalargenumberofclassesinordertosatisfyeverypossiblecombinationthatisneededsomanyclassesthatitbecomesimpractical.TheJavaI/Olibraryrequiresmanydifferentcombinationsoffeatures,andthisisthejustificationforusingthedecoratorpattern.Thereisadrawbacktothedecoratorpattern,however.Decoratorsgiveyoumuchmoreflexibilitywhileyourewritingaprogram(sinceyoucaneasilymixandmatchattributes),buttheyaddcomplexitytoyourcode.ThereasonthattheJavaI/Olibraryisawkwardtouseisthatyoumustcreatemanyclassesthe“core”I/OtypeplusallthedecoratorsinordertogetthesingleI/Oobjectthatyouwant.TheclassesthatprovidethedecoratorinterfacetocontrolaparticularInputStreamorOutputStreamaretheFilterInputStreamandFilterOutputStream,whichdonthaveveryintuitivenames.FilterInputStreamandFilterOutputStreamarederivedfromthebaseclassesoftheI/Olibrary,InputStreamandOutputStream,whichisthekeyrequirementofthedecorator(sothatitprovidesthecommoninterfacetoalltheobjectsthatarebeingdecorated).ReadingfromanInputStreamwithFilterInputStreamTheFilterInputStreamclassesaccomplishtwosignificantlydifferentthings.DataInputStreamallowsyoutoreaddifferenttypesofprimitivedataaswellasStringobjects.(Allthemethodsstartwith“read,”suchasreadByte(),readFloat(),etc.)This,alongwithitscompanionDataOutputStream,allowsyoutomoveprimitivedatafromoneplacetoanotherviaastream.These“places”aredeterminedbytheclassesinTableTheremainingclassesmodifythewayanInputStreambehavesinternally:whetheritsbufferedorunbuffered,ifitkeepstrackofthelinesitsreading(allowingyoutoaskforlinenumbersorsetthelinenumber),andwhetheryoucanpushbackasinglecharacter.Thelasttwoclasseslookalotlikesupportforbuildingacompiler(thatis,theywereprobablyaddedtosupporttheconstructionoftheJavacompiler),soyouprobablywontusethemingeneralprogramming.Youllneedtobufferyourinputalmosteverytime,regardlessoftheI/Odeviceyoureconnectingto,soitwouldhavemademoresensefortheI/Olibrarytomakeaspecialcase(orsimplyamethodcall)forunbufferedinputratherthanbufferedinput.WritingtoanOutputStreamwithFilterOutputStreamThecomplementtoDataInputStreamisDataOutputStream,whichformatseachoftheprimitivetypesandStringobjectsontoastreaminsuchawaythatanyDataInputStream,onanymachine,canreadthem.Allthemethodsstartwith“write,”suchaswriteByte(),writeFloat(),etc.TheoriginalintentofPrintStreamwastoprintalloftheprimitivedatatypesandStringobjectsinaviewableformat.ThisisdifferentfromDataOutputStream,whosegoalistoputdataelementsonastreaminawaythatDataInputStreamcanportablyreconstructthem.ThetwoimportantmethodsinPrintStreamareprint()andprintln(),whichareoverloadedtoprintallthevarioustypes.Thedifferencebetweenprint()andprintln()isthatthelatteraddsanewlinewhenitsdone.PrintStreamcanbeproblematicbecauseittrapsallIOExceptions(YoumustexplicitlytesttheerrorstatuswithcheckError(),whichreturnstrueifanerrorhasoccurred).Also,PrintStreamdoesntinternationalizeproperlyanddoesnthandlelinebreaksinaplatform-independentway.Readers&WritersJava1.1madesomesignificantmodificationstothefundamentalI/Ostreamlibrary.WhenyouseetheReaderandWriterclasses,yourfirstthought(likemine)mightbethattheseweremeanttoreplacetheInputStreamandOutputStreamclasses.Butthatsnotthecase.Althoughsomeaspectsoftheoriginalstreamslibraryaredeprecated(ifyouusethemyouwillreceiveawarningfromthecompiler),theInputStreamandOutputStreamclassesstillprovidevaluablefunctionalityintheformofbyte-orientedI/O,whereastheReaderandWriterclassesprovideUnicode-compliant,character-basedI/O.Inaddition:1.Java1.1addednewclassesintotheInputStreamandOutputStreamhierarchy,soitsobviousthosehierarchieswerentbeingreplaced.2.Therearetimeswhenyoumustuseclassesfromthe“byte”hierarchyincombinationwithclassesinthe“character”hierarchy.Toaccomplishthis,thereare“adapter”classes:InputStreamReaderconvertsanInputStreamtoaReaderandOutputStreamWriterconvertsanOutputStreamtoaWriter.ThemostimportantreasonfortheReaderandWriterhierarchiesisforinternationalization.TheoldI/Ostreamhierarchysupportsonly8-bitbytestreamsanddoesnthandlethe16-bitUnicodecharacterswell.SinceUnicodeisusedforinternationalization(andJavasnativecharis16-bitUnicode),theReaderandWriterhierarchieswereaddedtosupportUnicodeinallI/Ooperations.Inaddition,thenewlibrariesaredesignedforfasteroperationsthantheold.Asisthepracticeinthisbook,Iwillattempttoprovideanoverviewoftheclasses,butassumethatyouwillusetheJDKdocumentationtodetermineallthedetails,suchastheexhaustivelistofmethods.SourcesandsinksofdataAlmostalloftheoriginalJavaI/OstreamclasseshavecorrespondingReaderandWriterclassestoprovidenativeUnicodemanipulation.However,therearesomeplaceswherethebyte-orientedInputStreamsandOutputStreamsarethecorrectsolution;inparticular,thejava.util.ziplibrariesarebyte-orientedratherthanchar-oriented.SothemostsensibleapproachtotakeistotrytousetheReaderandWriterclasseswheneveryoucan,andyoulldiscoverthesituationswhenyouhavetousethebyte-orientedlibraries,becauseyourcodewontcompile.Offbyitself:RandomSQLServer2000FileRandomSQLServer2000Fileisusedforfilescontainingrecordsofknownsizesothatyoucanmovefromonerecordtoanotherusingseek(),thenreadorchangetherecords.Therecordsdonthavetobethesamesize;youjusthavetobeabletodeterminehowbigtheyareandwheretheyareplacedinthefile.AtfirstitsalittlebithardtobelievethatRandomSQLServer2000FileisnotpartoftheInputStreamorOutputStreamhierarchy.However,ithasnoassociationwiththosehierarchiesotherthanthatithappenstoimplementtheDataInputandDataOutputinterfaces(whicharealsoimplementedbyDataInputStreamandDataOutputStream).ItdoesntevenuseanyofthefunctionalityoftheexistingInputStreamorOutputStreamclasses;itsacompletelyseparateclass,writtenfromscratch,withallofitsown(mostlynative)methods.ThereasonforthismaybethatRandomSQLServer2000FilehasessentiallydifferentbehaviorthantheotherI/Otypes,sinceyoucanmoveforwardandbackwardwithinafile.Inanyevent,itstandsalone,asadirectdescendantofObject.Essentially,aRandomSQLServer2000FileworkslikeaDataInputStreampastedtogetherwithaDataOutputStream,alongwiththemethodsgetFilePointer()tofindoutwhereyouareinthefile,seek()tomovetoanewpointinthefile,andlength()todeterminethemaximumsizeofthefile.Inaddition,theconstructorsrequireasecondargument(identicaltofopen()inC)indicatingwhetheryouarejustrandomlyreading(“r”)orreadingandwriting(“rw”).Theresnosupportforwrite-onlyfiles,whichcouldsuggestthatRandomSQLServer2000FilemighthaveworkedwellifitwereinheritedfromDataInputStream.TheseekingmethodsareavailableonlyinRandomSQLServer2000File,whichworksforfilesonly.BufferedInputStreamdoesallowyoutomark()aposition(whosevalueisheldinasingleinternalvariable)andreset()tothatposition,butthisislimitedandnotveryuseful.Most,ifnotall,oftheRandomSQLServer2000FilefunctionalityissupercededinJDK1.4withtheniomemory-mappedfiles.Inputstreams1.BufferedinputfileToopenafileforcharacterinput,youuseaFileInputReaderwithaStringoraFileobjectasthefilename.Forspeed,youllwantthatfiletobebufferedsoyougivetheresultingreferencetotheconstructorforaBufferedReader.SinceBufferedReaderalsoprovidesthereadLine()method,thisisyourfinalobjectandtheinterfaceyoureadfrom.Whenyoureachtheendofthefile,readLine()returnsnullsothatisusedtobreakoutofthewhileloop.TheStrings2isusedtoaccumulatetheentirecontentsofthefile(includingnewlinesthatmustbeaddedsincereadLine()stripsthemoff).s2isthenusedinthelaterportionsofthisprogram.Finally,close()iscalledtoclosethefile.Technically,close()willbecalledwhenfinalize()runs,andthisissupposedtohappen(whetherornotgarbagecollectionoccurs)astheprogramexits.However,thishasbeeninconsistentlyimplemented,sotheonlysafeapproachistoexplicitlycallclose()forfiles.Section1bshowshowyoucanwrapSrreadingconsoleinput.System.inisanInputStream,andBufferedReaderneedsaReaderargument,soInputStreamReaderisbroughtintoperformtheadaptation.2.InputfrommemoryThissectiontakestheStrings2thatnowcontainstheentirecontentsofthefileandusesittocreateaStringReader.Thenread()isusedtoreadeachcharacteroneatatimeandsenditouttotheconsole.Notethatread()returnsthenextbyteasanintandthusitmustbecasttoachartoprintproperly.3.FormattedmemoryinputToread“formatted”data,youuseaDataInputStream,whichisabyte-orientedI/Oclass(ratherthanchar-oriented).ThusyoumustuseallInputStreamclassesratherthanReaderclasses.Ofcourse,youcanreadanything(suchasafile)asbytesusingInputStreamclasses,buthereaStringisused.ToconverttheStringtoanarrayofbytes,whichiswhatisappropriateforaByteArrayInputStream,StringhasagetBytes()methodtodothejob.Atthatpoint,youhaveanappropriateInputStreamtohandtoDataInputStream.IfyoureadthecharactersfromaDataInputStreamonebyteatatimeusingreadByte(),anybytevalueisalegitimateresult,sothereturnvaluecannotbeusedtodetecttheendofinput.Instead,youcanusetheavailable()methodtofindouthowmanymorecharactersareavailable.Heresanexamplethatshowshowtoreadafileonebyteatatime:/:c12:TestEOF.java/Testingforendoffilewhilereadingabyteatatime.importjava.io.*;publicclassTestEOF/Throwexceptionstoconsole:publicstaticvoidmain(Stringargs)throwsIOExceptionDataInputStreamin=newDataInputStream(newBufferedInputStream(newFileInputStream(TestEOF.java);while(in.available()!=0)System.out.print(char)in.readByte();/:Notethatavailable()worksdifferentlydependingonwhatsortofmediumyourereadingfrom;itsliterally“thenumberofbytesthatcanbereadwithoutblocking.”Withafile,thismeansthewholefile,butwithadifferentkindofstreamthismightnotbetrue,souseitthoughtfully.Youcouldalsodetecttheendofinputincaseslikethesebycatchinganexception.However,theuseofexceptionsforcontrolflowisconsideredamisuseofthatfeature.4.FileoutputThisexamplealsoshowshowtowritedatatoafile.First,aFileWriteriscreatedtoconnecttothefile.YoullvirtuallyalwayswanttobuffertheoutputbywrappingitinaBufferedWriter(tryremovingthiswrappingtoseetheimpactontheperformancebufferingtendstodramaticallyincreaseperformanceofI/Ooperations).ThenfortheformattingitsturnedintoaPrintWriter.Thedatafilecreatedthiswayisreadableasanordinarytextfile.Asthelinesarewrittentothefile,linenumbersareadded.NotethatLineNumberInputStreamisnotused,becauseitsasillyclassandyoudontneedit.Asshownhere,itstrivialtokeeptrackofyourownlinenumbers.Whentheinputstreamisexhausted,readLine()returnsnull.Youllseeanexplicitclose()forout1,becauseifyoudontcallclose()forallyouroutputfiles,youmightdiscoverthatthebuffersdontgetflushed,sotheyreincomplete.OutputstreamsThetwoprimarykindsofoutputstreamsareseparatedbythewaytheywritedata;onewritesitforhumanconsumption,andtheotherwritesittobereacquiredbyaDataInputStream.TheRandomSQLServer2000Filestandsalone,althoughitsdataformatiscompatiblewiththeDataInputStreamandDataOutputStream.5.StoringandrecoveringdataAPrintWriterformatsdatasothatitsreadablebyahuman.However,tooutputdataforrecoverybyanotherstream,youuseaDataOutputStreamtowritethedataandaDataInputStreamtorecoverthedata.Ofcourse,thesestreamscouldbeanything,buthereafileisused,buffered

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论