已阅读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年贵州初中化学必修一第二章期中测试卷
- 2026年天津市苏教版高二化学下册第7章知识点巩固习题
- 辽阳市第十中学2027届化学九年级第一学期期中经典模拟试题含解析
- 2026年小学教师资格考试综合素质历年真题战解析
- 2027届深圳市外国语学校九上化学期末统考试题含解析
- 肌张力评定考试试题及参考答案
- SEMI 3D6-2022 中文版 3D 集成 TSV 微凸点工艺与质量管控指南
- 黑龙江省龙东地区2026年中考历史真题真卷附答案
- 2026年乡镇综合行政执法队考试真题及答案
- 标准化职工食堂考核标准
- ISO9001-2026 核心数字记录与数据安全控制程序
- 2026年预防接种上岗培训考核试题(含答案)
- (正式版)DB11∕T 2332-2024 《危险化学品企业安全操作规程编制要求》
- 卫生院职工绩效评价手册
- 2026新教材语文 三年级上册第七单元22 《读不完的大书》说课教学课件
- 2026年文旅行业安全生产试题及答案
- DG-TJ08-2222-2026 城镇排水管道设计标准
- 肝脓肿诊疗专家共识(2025版)
评论
0/150
提交评论