已阅读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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026年广东省汕头市潮南区峡山义英初级中学3月英语模拟试卷(含答案)
- 2025 学画画作文课件
- 数字化转型下B银行ATM运营管理的优化与创新研究
- 检验类之临床医学检验技术(中级)阶段测测试题及答案
- Axure网站与App原型设计(全彩慕课版)(AxureRP10)- 教案 第11、12章 去哪儿网站高保真原型设计、产品经理的职能
- 数字化画笔:计算机辅助教学在中学美术课堂的创新实践与影响探究
- 数字化浪潮下我国家电行业电子商务应用的全景洞察与破局之道
- 数字化浪潮下图书馆虚拟参考咨询服务的创新变革与发展路径
- 数字化浪潮下XJ大学出版社计算机类教材营销策略的创新与突破
- 中考历史总复习第五单元隋唐时期:繁荣与开放的时代
- 互联网平台用户服务与纠纷处理手册(标准版)
- 2026天津师范大学第二批招聘 (辅导员、专业技术辅助岗位)27人考试参考题库及答案解析
- 第6课 少让父母操心 第1课时 课件+视频 2025-2026学年道德与法治三年级下册统编版
- 医院保安工作考核制度
- 物联网技术在小学环境教育中的应用效果课题报告教学研究课题报告
- 砌体墙体裂缝处理方案
- 罪犯评估中心制度规范
- 装备维护保养规范制度
- 营销2.0系统培训课件
- 新能源汽车高压系统检修课件 任务二新能源汽车高压电控总成故障检修 学习活动1 电机控制器故障检修
- (2025)精索静脉曲张中西医结合诊断治疗指南解读课件
评论
0/150
提交评论