下载
加入VIP
  • 专属下载特权
  • 现金文档折扣购买
  • VIP免费专区
  • 千万文档免费下载

上传资料

关闭

关闭

关闭

封号提示

内容

首页 io

io.pdf

io

luce
2013-07-17 0人阅读 举报 0 0 暂无简介

简介:本文档为《iopdf》,可适用于IT/计算机领域

Input,OutputandExceptionsCOMSWIntroductiontoComputerScienceChristopherConwayJuneInputvsOutputWedefineinputandoutputfromtheperspectiveoftheprogrammer•Inputisdatathatcomesintotheprogram,eg,fromafileorfromthekeyboardintoaprogramvariable•Ouputisdatathatgoesoutoftheprogram,eg,intoafileortothescreenBytevsCharacterStreamsJavahastwokindsofIOstreams:bytestreamsandcharacterstreams•BytestreamsoperateonarbitrarybinarydataTheparentclassesofbytestreamsareInputStreamandOutputStream•CharacterstreamsoperateontextualdataTheparentclassesofcharacterstreamsareReaderandWriterpublicabstractclassInputStream{*returnsavalue,*orforendofinput*publicabstractintread()*readcountbytesintobufatoffset*publicintread(bytebuf,intoffset,intcount){}*fillbuf*publicintread(bytebuf){}publiclongskip(longcount){}*howmanybytesareavailable*publicintavailable(){}publicvoidclose(){}}publicabstractclassReader{*returnsavalue,*orforendofinput*publicabstractintread()*readcountbytesintobufatoffset*publicintread(charbuf,intoffset,intcount){}*fillbuf*publicintread(charbuf){}publiclongskip(longcount){}*isthereinputready*publicbooleanready(){}publicvoidclose(){}}publicabstractclassOutputStream{*writesbasabyte*publicabstractvoidwrite(intb)*writecountbytesfrombufatoffset*publicvoidwrite(bytebuf,intoffset,intcount){}*writetheentirebuf*publicvoidwrite(bytebuf){}*writeanybufferedvalues*publicvoidflush(){}publicvoidclose(){}}publicabstractclassWriter{*writeschasachar*publicabstractvoidwrite(intch)*writecountbytesfrombufatoffset*publicvoidwrite(charbuf,intoffset,intcount){}*writetheentirebuf*publicvoidwrite(charbuf){}publicvoidwrite(Stringstr,intoffset,intcount){}publicvoidwrite(Stringstr){{*writeanybufferedvalues*publicvoidflush(){}publicvoidclose(){}}ConversionStreamsClassesareprovidedthatconvertbetweenbyteandcharacterIO•InputStreamReadertakesabyteinputstreamasitssourceandproducestheequivalentcharacterinput•OutputStreamWritertakeabyteoutputstreamasitstargetandconvertscharacteroutputintotheequivalentbyteformFileStreamsThefilestreams(FileInputStream,FileOutputStream,FileReaderandFileWriter)enablebyteandcharacterIOwithfilesEachhasaconstructorthattakesafilenameStringandreturnsthecorrespondingstreamIfyougiveafileoutputstreamthenameofafilethatdoesn’texist,itwillcreatethefile,ifpossibleFilterStreamsSomestreamsaredefinedbywheretheygettheirdata(orputit)othersaredefinedbywhattheydotothedata•Ordinarystreamsreadandwritedatafromaparticularsource,eg,afile,orabytearray•Filterstreamsprocessdatathatcomesinfromorgoesouttoanotherdatastream,eg,bufferingstreams,compressingdecompressingstreamsFilterStreams:ExamplesInputStreaminFile=newFileInputStream("foogz")intdata=inFileread()*datacontainsbyteofgzipcompresseddata*InputStreaminFile=newGZipInputStream(inFile)data=inFileread()*datacontainsbyteofdecompresseddata*OutputStreamoile=newGZipOutputStream(newFileOutputStream("bargz"))oilewrite()*bargzcontainscompressedbyteofdata*BufferedStreamsNoteveryfilterstreamhastotransformthedataThebufferedstreams(BufferedInputStream,BufferedOutputStream,BufferedReaderandBufferedWriter)makeIOmoreefficientbyreadingandwritinginlargeblocksInsteadofoneaccesstodiskforeverycalltoreadorwrite,abufferedstreamputsachunkofdataintoabufferinmemorycallstoreadorwriteactonthebufferuntilitrunsoutNote:itisoftennecessarytocallflush()toforceoutputonabufferedoutputstreamLineNumberReaderTheLineNumberReaderinputstreamwrapsacharacterinputstreamandkeepstrackoflinesreadThemethodgetLineNumber()returnsthenumberoflinesseenssofarLineNumberReaderin=newLineNumberReader(newFileReader("inputtxt"))Stringlinewhile((line=inreadLine())!=){Systemoutprintln("Line"ingetLineNumber()":"line)}PrintStreamsTheprintoutputstreams(PrintStreamandPrintWriter)arefilterstreamsthatprovideprintandprintlnmethodsthattakeanyofthebasictypesasparametersTheprintstreamsoutputcharacterdata,ie,println()isoutputas""(abytecharacterstring)SystemoutandSystemerrarestaticPrintStreamobjectsSysteminisanInputStreamDataStreamsThedatastreams(DataInputStreamandDataOutputStream)provideconveniencemethodsforreadingandwritingallofthebasictypesasbinarydataIe,writeInt()isoutputas(abitbinaryencodedinteger)ThedatastreammethodsareoftheformreadIntwriteInt,readBooleanwriteBoolean,readFloatwriteFloat,etcNetworkStreamsJavaallowsyoutoaccessafileontheInternetaseasilyasyou’daccessafileonyourowncomputerTheclassjavanetURLrepresentsanetworkresourceURLurl=newURL("http:wwwcolumbiaedu")InputStreamin=urlopenStream()intchwhile((ch=inread())!=){}ExceptionsIOprovidesmanyopportunitiesforunexpectederrorsWhatiftheuserdeletesafilewhilewearetryingtoreaditWhatifthenetworkconnectiongoesdeadwhilewetrytoconnecttoaURLWecallunexpectedeventsinthelifeofaprogramexceptionsJavaprovidesamechanismforhandlingexceptionsgracefullyExceptions:Ifamethodgenerates(throws)anexception,itmustdeclarethatexceptioninathrowsclauseEg,alloftheInputStreammethodsthrowIOException:publicabstractintread()throwsIOExceptionIfamethodcallsanothermethodthatmaythrowanexception,itmust:•throwtheexceptionitself(declareitinathrowsclause),or•handle(catch)theexceptionTheExecutionStackWhenanexceptionisthrown,executionstopsimmediatelyandcontrolistransferredtothecallingmethodIftheexceptionisnotcaught,controlisimmediatelytransferredtothemethodthatcalledthatmethodAndsoonThischainofmethodcallsiscalledtheexecutionstackThisiswhatyouseewhenanexceptionspillsthroughtotheterminal(eg,aPointerException):alistofmethodnamesandlinenumbersdetailingatwhatpointtheexceptionwasthrownandhowexecutionreachedthatpointCatchingExceptionsExceptionsarehandledusingatrycatchblockCodethatmaythrowanexceptionisputinsideatryblock,followedbycatchclausesthatmatchaparticularexceptiontry{InputStreaminFile=newFileInputStream("atxt")intch=inFileread()}catch(FileNotFoundExceptione){Systemerrprintln("Nofileatxt")}catch(IOExceptione){Systemerrprintln("Errorreadingatxt")}ExceptionTypesExceptionisasubclassofThrowableParticularexceptionssubclassExceptiontoprovidemoredescriptiveerrorinformationExceptionhasamethodgetMessage()thatreturnsadescriptionoftheerrorencounteredtry{InputStreaminFile=newFileInputStream("atxt")}catch(FileNotFoundExceptione){Systemerrprintln(egetMessage())*"atxt(Nosuchfileordirectory)"*}ExceptionTypes:Whenanexceptionisthrown,thefirstassignmentcompatiblecatchclausewillmatchThatmeansthatsupertypeclauseswillhandlesubtypeexceptionstry{InputStreaminFile=newFileInputStream("atxt")intch=inFileread()}catch(Exceptione){*Thisclausecatcheseverything*Systemerrprintln("Generalerror")}catch(FileNotFoundExceptione){*Thisclausewillneverexecute*Systemerrprintln("Specificerror")}ThefinallyClauseAtrycatchblockcanhaveafinallyclausecontainingcodetobeexecutedwhetherornotanexceptionisthrownAfinallyclauseistypicallyusedtocloseanyopenstreamsandcleanupanyinternalstatetry{intch=inStreamread()}catch(IOExceptione){Systemerrprintln(egetMessage())}finally{inStreamclose()*Thestreamgetsclosedwhetherornot*thereadsucceeds*}ExceptionsInsideHandlersIfanexceptionisthrowninsideacatchorfinallyclause,itwillnotbehandledinsidethesametryblockexecutionwillhaltandcontrolwillbesenttothenextmethodupthestackInputStreaminFile=try{inFile=newFileInputStream("atxt")}catch(FileNotFoundExceptione){inFile=newFileInputStream("atxt")*Callingmethodmusthandle*FileNotFoundException*}UncheckedExceptionsYoumaybewonderingwhyyou’veneverbeenaskedtocatchaPointerExceptionPointerExceptionisasubclassofRuntimeException,theparentclassofalluncheckedexceptionsMethodsthatthrowuncheckedexceptionsarenotrequiredtobeenclosedinatrycatchblockOtheruncheckedexceptionsare:•ArrayIndexOutOfBoundsException•ClassCastException•ArithmeticExceptionErrorsErrorissubclassofThrowablethatencompassesruntimeerrorsthataretooserioustobecaughtSomesubclassesofErrorthatyou’veprobablyspentsometimewith:•NoClassDefFoundError•NoSuchMethodErrorDefiningExceptionsTocreateyourownexception,extendExceptionAnexceptionshouldprovideaconstructorthattakesinformationaboutthenatureoftheerrorandpassesittoExceptionasamessagepublicclassReallyBadExceptionextendsException{publicReallyBadException(intbadness){super("Areallybadexceptionoccured:"badness"outof")}}ObjectSerializationWe’vetalkedabouthowtoreadandwritecharacterdataandbinarydataofaprimitivetypeWhatifwewanttodoIOonanobjectTheprocessofreadingorwritinganobjecttoanIOstreamiscalledobjectserializationThestreamsthatreadandwriteobjectdataareObjectInputStreamandObjectOutputStreamObjectsareserializedanddeserializedusingthemethodswriteObjectandreadObjectObjectSerialization:•InvokingwriteObjectcausesallofthenonstaticfieldsoftheobjecttobewrittentothestream•Ifafieldisofanobjecttype,thefielditselfwillbeserialized•Theserializationprocessdoesnotjustoperateonasingleobject:itoperatesonanentiresetofobjectsthatcanbereachedthroughthereferencesstartingwiththatobject(areferencegraph)•InvokingreadObjectreconstitutesthereferencegraphandreturnsareferencetotheroot(ie,theoriginalobject)Serializable•AclassindicatesitcanbeserializedbyimplementingtheSerializableinterfaceTheinterfacehasnomethodsitisamarkerinterface•AnyobjectfieldsoftheclassshouldalsobeSerializable•Iftheclassisasubclass,itsparentmusthaveanoargconstructororitselfbeSerializableimportjavaio*publicclassFooimplementsSerializable{privateintx,ypublicFoo(intx,inty){thisx=xthisy=y}publicstaticvoidmain(Stringargs){try{Fooa=newFoo(,)ObjectOutputStreamout=newObjectOutputStream(newFileOutputStream("atmp"))outwriteObject(a)ObjectInputStreamin=newObjectInputStream(newFileInputStream("atmp"))Foob=(Foo)inreadObject()}catch(IOExceptione){Systemerrprintln(egetMessage())}}}ObjectVersions•TheserializationprocessassignsaversionIDtoeveryclassIfwechangeanythingabouttheclass,theversionIDwillchange•Inordertodeserializeaclass,theversionIDoftheserializedversionmustexactlymatchthatoftheclassfileAnattempttodeserializeanonmatchingclasswillcauseanInvalidClassException•Tomakesuperficiallydissimilarversionsofaclasscompatiblewithrespecttoserialization,wecandefinetheconstant:publicstaticfinallongserialVersionUIDTransientFieldsFieldsmarkedwiththemodifiertransientarenotserializedAsthenameindicates,theyareusuallyvaluesthataren’tpartoftheobjectspermanentstatepublicclassCircleimplementsSerializable{privatedoublerprivatetransientdoubleareapublicCircle(doubler){thisr=rarea=MathPI*r*r}}CustomizingSerializationIfdumpingalloftheobject’sfieldsisn’twhatwewanttodo,wecandefinethemethodswriteObjectandreadObjectprivatevoidwriteObject(ObjectOutputStreamout)throwsIOExceptionprivatevoidreadObject(ObjectInputStreamin)throwsIOExceptionAclassthatdefinesthesemethodstakesresponsibilityforserializingitsownfields

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

文档小程序码

使用微信“扫一扫”扫码寻找文档

1

打开微信

2

扫描小程序码

3

发布寻找信息

4

等待寻找结果

我知道了
评分:

/35

io

VIP

在线
客服

免费
邮箱

爱问共享资料服务号

扫描关注领取更多福利