BasicInput/OutputinJava
CS4354SummerII2014!
JillSeaman Readingfromthescreen(Input) •Scannerclass(injava.util) ✦Allowstheusertoreadvaluesofvarioustypesfromastreamofcharacters. ✦Therearetwoconstructorsthatareparticularlyuseful:onetakesanInputStreamobjectasaparameterandtheothertakesaFileReaderobjectasaparameter. !
Scannerin=newScanner(System.in);"//System.inistheInputStreamassociatedwiththekeyboard"!
!
!
ScannerinFile=newScanner(newFileReader("myFile"));
1 2 Readingfromthescreen(Input) Readingfromthescreen(Input) •UsefulScannermethods: ✦intnextInt()Returnsthenexttokenasanint.Ifthenexttokenisnotaninteger,InputMismatchExceptionisthrown. ✦longnextLong()Similar ✦floatnextFloat()Similar ✦doublenextDouble()Similar ✦StringnextLine()Returnstherestofthecurrentline,excludinganylineseparatorattheend. ✦booleanhasNextInt()Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasanintvalueusingthenextInt()method. ✦hasNextLong(),hasNextFloat(),etc. •ExampleusingaScannerwithSystem.in: Scannersc=newScanner(System.in);"System.out.println("Enterthequantity:");"inti=sc.nextInt();"System.out.println("Entertheprice:");"price=sc.nextDouble();"System.out.println("Enterthename:");"sc.nextLine();//skiptoendofpreviousline"name=sc.nextLine();"
3 4 Writingtothescreen(Output) •System.out(injava.lang) ✦System.outisaPrintStream,usedtoprintcharacters.✦APrintStreamprovidestheabilitytoprintrepresentationsofvarious datavaluesconveniently. •println(x)andprint(x) ✦MethodsofPrintStream(seeAPIwebsitefordetails)✦Overloadedtoprintallthevariousdatatypes.✦OftenusesthedefaulttoString()methodofthewrapperclasses. -forexample,Integer.toString(inti)toprintanint✦Thedifferencebetweenprint()andprintln()isthatthelatteraddsa newlinewhenit’sdone.
5 Writingtothescreen:Formatting •DecimalFormatclass,usedtoformatdecimalnumbers ✦DecimalFormat(Stringpattern)CreatesaDecimalFormatusingthegivenpattern. ✦format(x)producesastringbyformattinganitem(x)ordingtotheobjectspattern. ✦Thefollowingcharactershavespecialmeaninginapattern(othercharactersaretakenliterally,appearinginthestringunchanged). 0digit(left-paddedwithzeros)#digit,zeroshowsasabsent(no0padding).decimalseparator,GroupingseparatorESeparatesmantissaandexponentinscientificnotation%Multiplyby100,showaspercent
6 Formattingexample Formattingexample importjava.text.*;"" classFormatOut{" •OutputfromrunningFormatOut: publicstaticvoidmain(Stringargs[]){" int[]iArray={1,12,123};" float[]fArray={1.1F,10.12F,100.123F};" 01" double[]dArray={1.1,10.12,100.1234,1000.1239};" "DecimalFormatdfi=newDecimalFormat("#00");"DecimalFormatdff=newDecimalFormat("#00.00float");"DecimalFormatdfd=newDecimalFormat("#000.000");" "for(inti=0;i7
8
Objectserialization
•Aprocessoftransforminganobjectintoastreamofbytes,tobesavedinafile.
•Objectserializationallowsyoutoimplementpersistence:•Persistence:whenanobject’slifetimeisnotdeterminedbywhether
aprogramisexecuting;theobjectexistsinbetweeninvocationsoftheprogram.•Theobject’sclassmustimplementtheSerializableinterface.
!
publicclassCircleimplementsSerializable{...✦Ifnot,yougetanexception:java.io.NotSerializableException:theClass✦Note:therearenorequiredmethodstooverride✦Theinstancevariabletypesmustbeserializabletoo.
9 Objectserialization:streams •Javaprovidestwoobjectstreamsforserialization. ✦ThesearebothinitializedgivenaFileOutputStreamandaFileInputStream(respectively).Theexampleshowshowtoinitializethesegivenafilename. •ObjectOutputStream" ✦ThewriteObj()methodwritesanobjecttotheoutputstream,convertingallthedataintheobjecttobytes. ✦Allthefieldobjectsintheclassmustalsobeserializable •ObjectInputStream" ✦ThereadObj()methodreadsanobjectfromtheinputstream.✦TheobjectwasmostlikelywrittenusingwriteObj✦Youmustcasttheresulttothecorrectobject. 10 Serializationexample:ZStudent.java importjava.io.*;" !
//Simplestudentclass"classZStudentimplementsSerializable{" intno;"Stringfirst,mid,last;"floatave;" "ZStudent(){};//defaultconstructor"ZStudent(intno,Stringfirst,Stringmid, this.no=no;"this.first=first;"this.mid=mid;"this.last=last;"this.ave=ave;"}" "publicStringdisplay(){" return(no+""+first+""+mid+}"} Stringlast,""+last+ float""+ ave){"ave);" 11 Serializationexample:ObjFIO.javacont. importjava.io.*;"classObjFIO{" publicstaticvoidmain(String[]args){"ZStudent[]zstudents={"newZStudent(50,"Blue","M","Monday",50.0F),"newZStudent(100,"Gray","G","Tuesday",60.0F),"newZStudent(150,"Green","G","Wednesday",70.0F),"newZStudent(200,"Pink","P","Thursday",80.0F),"newZStudent(300,"Red","R","Friday",90.0F)};" !
try{"FileOutputStreamfos=newFileOutputStream("zStudentFile");"ObjectOutputStreamoos=newObjectOutputStream(fos);""for(inti=0;i<5;i++){"oos.writeObject(zstudents[i]);//towrite1objatatime"}"fos.close();" }catch(IOExceptione){"System.out.println(“Problemwithfileoutput”);" } 12 Serializationexample:ObjFIO.javacont. try{"FileInputStreamfis=newFileInputStream("zStudentFile");"ObjectInputStreamois=newObjectInputStream(fis);"ZStudentstud;""//toreadoutstudentrecordsfromafile"for(inti=0;i<5;i++){"stud=(ZStudent)ois.readObject();//explicitcastreqd"System.out.println(stud.display());"}"fis.close();" ""}catch(FileNotFoundExceptione){"System.out.println(“Cannotfinddatafile.”);" }catch(IOExceptione){"System.out.println(“Problemwithfileinput.”);" }catch(ClassNotFoundExceptione){"System.out.println(“Classnotfoundoninputfromfile.”);" }"}"} 13 Serializationexample •Outputfromtheexample: !
50BlueMMonday50.0" 100GrayGTuesday60.0" !
150GreenGWednesday70.0" 200PinkPThursday80.0" !
300RedRFriday90.0 !
•Note:Arraysareobjects,andmaybeserializedasawhole: oos.writeObject(zstudents); ZStudent[]newStudents=(ZStudent[])ois.readObject();"for(inti=0;i<5;i++){" System.out.println(newStudents[i].display());"} 14
JillSeaman Readingfromthescreen(Input) •Scannerclass(injava.util) ✦Allowstheusertoreadvaluesofvarioustypesfromastreamofcharacters. ✦Therearetwoconstructorsthatareparticularlyuseful:onetakesanInputStreamobjectasaparameterandtheothertakesaFileReaderobjectasaparameter. !
Scannerin=newScanner(System.in);"//System.inistheInputStreamassociatedwiththekeyboard"!
!
!
ScannerinFile=newScanner(newFileReader("myFile"));
1 2 Readingfromthescreen(Input) Readingfromthescreen(Input) •UsefulScannermethods: ✦intnextInt()Returnsthenexttokenasanint.Ifthenexttokenisnotaninteger,InputMismatchExceptionisthrown. ✦longnextLong()Similar ✦floatnextFloat()Similar ✦doublenextDouble()Similar ✦StringnextLine()Returnstherestofthecurrentline,excludinganylineseparatorattheend. ✦booleanhasNextInt()Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasanintvalueusingthenextInt()method. ✦hasNextLong(),hasNextFloat(),etc. •ExampleusingaScannerwithSystem.in: Scannersc=newScanner(System.in);"System.out.println("Enterthequantity:");"inti=sc.nextInt();"System.out.println("Entertheprice:");"price=sc.nextDouble();"System.out.println("Enterthename:");"sc.nextLine();//skiptoendofpreviousline"name=sc.nextLine();"
3 4 Writingtothescreen(Output) •System.out(injava.lang) ✦System.outisaPrintStream,usedtoprintcharacters.✦APrintStreamprovidestheabilitytoprintrepresentationsofvarious datavaluesconveniently. •println(x)andprint(x) ✦MethodsofPrintStream(seeAPIwebsitefordetails)✦Overloadedtoprintallthevariousdatatypes.✦OftenusesthedefaulttoString()methodofthewrapperclasses. -forexample,Integer.toString(inti)toprintanint✦Thedifferencebetweenprint()andprintln()isthatthelatteraddsa newlinewhenit’sdone.
5 Writingtothescreen:Formatting •DecimalFormatclass,usedtoformatdecimalnumbers ✦DecimalFormat(Stringpattern)CreatesaDecimalFormatusingthegivenpattern. ✦format(x)producesastringbyformattinganitem(x)ordingtotheobjectspattern. ✦Thefollowingcharactershavespecialmeaninginapattern(othercharactersaretakenliterally,appearinginthestringunchanged). 0digit(left-paddedwithzeros)#digit,zeroshowsasabsent(no0padding).decimalseparator,GroupingseparatorESeparatesmantissaandexponentinscientificnotation%Multiplyby100,showaspercent
6 Formattingexample Formattingexample importjava.text.*;"" classFormatOut{" •OutputfromrunningFormatOut: publicstaticvoidmain(Stringargs[]){" int[]iArray={1,12,123};" float[]fArray={1.1F,10.12F,100.123F};" 01" double[]dArray={1.1,10.12,100.1234,1000.1239};" "DecimalFormatdfi=newDecimalFormat("#00");"DecimalFormatdff=newDecimalFormat("#00.00float");"DecimalFormatdfd=newDecimalFormat("#000.000");" "for(inti=0;i
publicclassCircleimplementsSerializable{...✦Ifnot,yougetanexception:java.io.NotSerializableException:theClass✦Note:therearenorequiredmethodstooverride✦Theinstancevariabletypesmustbeserializabletoo.
9 Objectserialization:streams •Javaprovidestwoobjectstreamsforserialization. ✦ThesearebothinitializedgivenaFileOutputStreamandaFileInputStream(respectively).Theexampleshowshowtoinitializethesegivenafilename. •ObjectOutputStream" ✦ThewriteObj()methodwritesanobjecttotheoutputstream,convertingallthedataintheobjecttobytes. ✦Allthefieldobjectsintheclassmustalsobeserializable •ObjectInputStream" ✦ThereadObj()methodreadsanobjectfromtheinputstream.✦TheobjectwasmostlikelywrittenusingwriteObj✦Youmustcasttheresulttothecorrectobject. 10 Serializationexample:ZStudent.java importjava.io.*;" !
//Simplestudentclass"classZStudentimplementsSerializable{" intno;"Stringfirst,mid,last;"floatave;" "ZStudent(){};//defaultconstructor"ZStudent(intno,Stringfirst,Stringmid, this.no=no;"this.first=first;"this.mid=mid;"this.last=last;"this.ave=ave;"}" "publicStringdisplay(){" return(no+""+first+""+mid+}"} Stringlast,""+last+ float""+ ave){"ave);" 11 Serializationexample:ObjFIO.javacont. importjava.io.*;"classObjFIO{" publicstaticvoidmain(String[]args){"ZStudent[]zstudents={"newZStudent(50,"Blue","M","Monday",50.0F),"newZStudent(100,"Gray","G","Tuesday",60.0F),"newZStudent(150,"Green","G","Wednesday",70.0F),"newZStudent(200,"Pink","P","Thursday",80.0F),"newZStudent(300,"Red","R","Friday",90.0F)};" !
try{"FileOutputStreamfos=newFileOutputStream("zStudentFile");"ObjectOutputStreamoos=newObjectOutputStream(fos);""for(inti=0;i<5;i++){"oos.writeObject(zstudents[i]);//towrite1objatatime"}"fos.close();" }catch(IOExceptione){"System.out.println(“Problemwithfileoutput”);" } 12 Serializationexample:ObjFIO.javacont. try{"FileInputStreamfis=newFileInputStream("zStudentFile");"ObjectInputStreamois=newObjectInputStream(fis);"ZStudentstud;""//toreadoutstudentrecordsfromafile"for(inti=0;i<5;i++){"stud=(ZStudent)ois.readObject();//explicitcastreqd"System.out.println(stud.display());"}"fis.close();" ""}catch(FileNotFoundExceptione){"System.out.println(“Cannotfinddatafile.”);" }catch(IOExceptione){"System.out.println(“Problemwithfileinput.”);" }catch(ClassNotFoundExceptione){"System.out.println(“Classnotfoundoninputfromfile.”);" }"}"} 13 Serializationexample •Outputfromtheexample: !
50BlueMMonday50.0" 100GrayGTuesday60.0" !
150GreenGWednesday70.0" 200PinkPThursday80.0" !
300RedRFriday90.0 !
•Note:Arraysareobjects,andmaybeserializedasawhole: oos.writeObject(zstudents); ZStudent[]newStudents=(ZStudent[])ois.readObject();"for(inti=0;i<5;i++){" System.out.println(newStudents[i].display());"} 14
声明:
该资讯来自于互联网网友发布,如有侵犯您的权益请联系我们。
上一篇校,文件隐藏了怎么恢复