CST141 Binary I/O Page 1

CST141--Binary I/O

Page 1

1 Binary I/O

1 BCSinTa1r4y1 I/O 2 CBSinTa1r4y1 Data 2 BiAnlal rdyatDaaistastored in computers in binary format

A?llAdllaotaneisss(t1o)readndinzceoromsp(u0t)ers in binary format T?eAxtll (oinncelsud(1in)gadnidgiztse)roiss c(o0n) verted to some coding scheme (ASCII, Unicode, etc.) TBfileienxatr(yindcoluedsinnogtdriegqitusi)reisccoonnvveerrstieodnst--o tshoembeincaordyinngumscehreicmvea(luAeSCisIIw, rUitnteicnoddeir,eecttcly.)to the Binary does not require conversions--the binary numeric value is written directly to the 3 InfpileutStream and OutputStream 3 InTphuetsSetarereamtheaanbdstOraucttpculatsSsterseafrmom which all binary input and output classes extend TAhneessepaerceiatllhyegaobosdtreaxcatmclpasleseosf finrohmeriwtahnicche farlol mbintahreyJianvpautAaPnId output classes extend AAsunllbmecsleaptsehscoeidsa)sllywfrghooimcohdamlel uxsaustmbbcplealescsoaefusginthhhtreorwitatnhceecfhroemckethdeIJOaEvxaceApPtIion (or one of its As?ullbMmculeaststhsboeeds)simwfrphooimcrhteamdll ufsrusotbmbcleajascvsaaeu.sgiothhtrow the checked IOException (or one of its 4 Th?eMBuinstarbye Iim/OpoCrtleadssfreosm java.io

45 The BFiilneaIrnypIu/tSOtrCelasmseCslass (Page 1)

5 ThUeseFdilefoIrncprueatStitnrgeianmpuCt lsatrsesams(Pthaagtere1a)d only positive byte numeric data from a file UAsseudbcfolarscsreoaf tIinnpguitnSpturet asmtreams that read only positive byte numeric data from a file A?sIunbhcelraitsss tohfeInrepaudtS()trmeaemthod that reads one byte of data to the stream L?ocInahteedritins tthhee rjeaavad.(i)ompaecthkoadgethat reads one byte of data to the stream Liomcpaotertdjianvath.ieo.jFaivleaI.niopuptaSctkraegame ;

6 ThiemFpiolertIjnapvua.tiSo.tFrieleaImnpuCtlSatsrseam(;Page 2)

6 ThFeorFmilaetI:nputStream Class (Page 2) FFoilremInapt:utStream fileInputStreamObject = new FileInputStream("path/filename"); FiTlehInropwustSatrjeaavma.ifoil.eFIinlepNuotStFtroeuanmdEOxbcjeepcttio=nnifewtheFilfeilIendpouetSstnreoatmex("isptath/filename"); TThhrroowwss aa jjaavvaa..iioo..FDiilreeNcototFryoNuontdFEoxucnedpEtixocnepifttiohne iffiltehdeofeosldneortoenxtishte drivedoes not exist ExTamhrpolwess:a java.io.DirectoryNotFoundException if the folder on the drivedoes not exist EFxilaemInppleust:Stream input = new FileInputStream("temp.dat");

FileInputStream input = new FileInputStream("temp.dat"); 7 The FileOutputStream Class (Page 1)

7 ThUeseFdilefoOructrepauttinSgtroeuatmputCslatrsesam(oPbajegcets1t)hat write only positive byte numeric data to a file

UfAilseseudbcfolarscsreoaf tOinugtpouuttSpturet asmtream objects that write only positive byte numeric data to a A?sIunbhcelraitsss tohfeOwurtipteu(t)Stmreeatmhod that writes one byte of data to the stream L?ocInahteedritins tthhee wjarvitae.(io) mpaectkhaogdethat writes one byte of data to the stream Liomcpaotertdjianvath.ieo.jFaivleaO.iuotppauctSktargeeam; 8 ThiemFpiolertOjauvtap.uiot.SFtilreeOaumtpuCtlSatsresam(;Page 2)

8 ThFeorFmilaetO: utputStream Class (Page 2) FFoilremOautt:putStream fileOutputStreamObject = new FileOutputStream("path/filename"); EFxilaemOpultepsu:tStream fileOutputStreamObject = new FileOutputStream("path/filename"); EFxilaemOpultepsu:tStream input = new FileOutputStream("temp.dat");

FileOutputStream input = new FileOutputStream("temp.dat"); 9 The read() Method

9 ThAemreeathdo(d) oMf ectlahsosdFileInputStream (inherited from FileStream) that reads the next byte

of data from the input stream--from the file)

AoFofmrdmaetataht:ofrdoomf

class FileInputStream (inherited the input stream--from the file)

from

FileStream)

that

reads

the

next

byte

FfoilremInaptu: tStreamObject.read();

EfxilaemInppluet:StreamObject.read();

Examples:

CST141--Binary I/OFbiyleteOcurtepduittSst=reainmpuint.pruetad=()n;ew FileOutputStream("temp.dat");

10 The write() Method

9 ThAemreeathdo(d) oMf ectlahsosdFileInputStream (inherited from FileStream) that writes a specified Abymteeothf oddatoaf tcolatshseFoiluetIpnuptutsStrtereaamm--(tionhthereitfeilde)from FileStream) that reads the next byte oFof rdmataat:from the input stream--from the file) FfoilremOautt:putStreamObject.write( byteValue ); EfxilaemInppluet:StreamObject.read(); Eoxuatmpuptl.ew: rite(credits);

11 FilebyItOe.jcarevdaits = input.read();

(Page 1)

102 TFihleIwOr.jiatev(a) Method

(Page 2)

13

FilAbeyImtOee.otjhfaodvdaatoaf tcolatshseFoiluetIpnuptutsStrtereaamm--(ti(onPhtahegreietfei3lde))from FileStream) that writes a specified

14 FilFeoIrOm.ajta:va

(Page 4)

15 FilefilIeOO.ujatpvuatStreamObject.write( byteV(Palaugee);5) Example:

16 FileouIOtp.ujat.vwarite(credits);

(Page 6)

117 FileteIrOS.jtarvea ms

(Page 1)

12 FilTehIeOF.jilatevraInputStream and FilterOutp(uPtaSgtreea2m) classes filter streams filter bytes for some purpose

13 FilSeuIbOcl.ajassveas of these two classes read(Paandgew3ri)te integers, floats, strings, characters and

14 FilbeoIoOle.ajanvsa

(Page 4)

18 The DataInputStream Class (Page 1)

15 FileIO.java

(Page 5)

"Wraps" around a FileInputStream object to give it the ability to read integers, floats,

16 FilsetrIiOng.jsa, vbaooleans and characters (Page 6)

17 FilAtesrubSctlraesas mofsFilterInputStream Located in the java.io package TsiomhmepeoFriplttuejarrpIvnoaps.iueot.SDtaretaaImnpauntdStFreilatemrO; utputStream classes filter streams filter bytes for

19 ThSeubDcalatsasIenspouf ttShterseeatmwoCclalassses(rPeaagdea2nd) write integers, floats, strings, characters and bForomleaatn:s

18 ThDeaDtaaItnapIuntpSturetSamtredaamtaICnlpaustsStre(PamagOebj1e)ct = new "WDraaptasI"napruotuSntrdeaamF(ilfeilIenIpnuptuSttSrteraemamoObbjejcetctt)o; give it the ability to read integers, floats, sEtxrainmgps,leb:ooleans and characters ADsautabIcnlapsustSotfreFailtmeriInnppuuttS=trneeawmDataInputStream( new FileInputStream( "temp.dat") );

20 ThLeocDaatetdaOinutthpeujtaSvtar.eioapmacCklaagses (Page 1)

"iWmrpaoprst"jaavrao.uion.dDatFaiIlenOpuuttSpturteSatmre;am object to give it the ability to write integers, 19 ThfleoaDtsa,tsatIrninpgus,tSbtoroeleaamnsCalandsscha(Praacgteers2)

FAosrumbactl:ass of FilterOutputStream LDoacatateIndpiuntSthtreeajamvad.iaotapIancpkuatgSetreamObject = new

imDpaotratIjnapvuat.Siot.rDeaamta(OfiuletIpnuptSuttrSetarema;mObject);

21 ThEexaDmaptlaeO: utputStream Class (Page 2)

FDoarmtaaInt:putStream input = new DataInputStream( new FileInputStream( "temp.dat") );

20 ThDeaDtaaOtauOtpuuttSpturetSamtredaamtaICnlpaustsStre(PamagOebj1e)ct = new "WDraaptasO" uatrpouutnSdtraeaFmile(OfiluetOpuuttpSutrteSatrmeaombOjebcjtetcot)g;ive it the ability to write integers, fEloxaamts,plset:rings, booleans and characters ADsautabOcluatspsuotfStFrieltaemrOiuntppuuttS=trneeawmDataOutputStream( new FileOutputStream( Loc"taetmedp.indatth"e) )ja; va.io package

22 PrimpitoirvtejaRveaa.iod.DMaetathOoudtpsuftoStrreCalams;s DataInputStream

(Page 1)

21

ThRsetereaDadamstpa--rOifmruoitmtpivueatsSfiilnterc)el:uadmingClinatsesge(rsP,aflgoeat2s,)booleans and characters from the input

FD??oaDrrreemtaaaataOddatBCuO: yhtuptateurp((tu)S)ttSretraemamd(aftilaeIOnuptuptuSttSretraemaOmbOjebcjetc=t);new

E?xraemapdlFel:oat()

Page 2

Example:

CST141--Binary I/ODataOutputStream input = new DataOutputStream( new FileOutputStream(

"temp.dat") );

22 Primitive Read Methods for Class DataInputStream

(Page 1)

Reads primitives including integers, floats, booleans and characters from the input stream--from a file):

? readByte()

? readChar()

? readFloat()

? readDouble()

? readInt()

? readLong()

? readShort()

? readBoolean()

23 Primitive Read Methods for Class DataInputStream

Format: dataInputStreamObject.readPrimitive();

Example: int credits = input.readInt();

(Page 2)

24 The readUTF() Method

A method of class DataInputStream that reads a series of bytes from the input stream that are in UTF-8 format and converts them into a string

Format: dataInputStreamObject.readUTF();

Example: String firstName = input.readUTF();

25 Primitive Write Methods for Class DataOutputStream

(Page 1)

Writes primitives including integers, floats, booleans and characters to the output

stream--to a file):

? writeByte()

? writeChar()

? writeFloat()

? writeDouble()

? writeInt()

? writeLong()

? writeShort()

? writeBoolean()

26 Primitive Write Methods for Class DataOutputStream Format: dataOutputStreamObject.writePrimitive(); Example: output.writeInt(credits);

(Page 2)

27 The writeUTF() Method

A method of class DataInputString that converts a series of bytes into a string (UTF-8 format) and writes them into the output stream

Format: dataInputStreamObject.readUTF();

Example: ouput.readUTF(firstName);

28 DataIOStream.java

(Page 1)

29 DataIOStream.java

(Page 2)

30 DataIOStream.java

(Page 3)

Page 3

class DataInputStream

CST141--Binary I/O? Use a for loop to iterate through and read the three fields for all records from the

input object into a StringBuilder object with appropriate labels (see example above)

? Display all the data in a showMessageDialog()

38 BinaryMiniQuiz1.java

(Page 3)

39 The BufferedInputStream Class (Page 1)

"Wraps" around a FileInputStream object to speed up input by reducing the number of disk reads

The whole block of data is read into the RAM buffer at once

40 The BufferedInputStream Class (Page 2) A subclass of FilterInputStream It has no methods of its own--all are inherited from InputStream Located in the java.io package import java.io.BufferedInputStream;

41 The BufferedInputStream Class (Page 3)

Format: BufferedInputStream bufferedInputStreamObject = new BufferedInputStream( fileInputStreamObject );

Example: BufferedInputStream input = new BufferedInputStream( new FileInputStream( "temp.dat") );

42 The BufferedInputStream Class (Page 4)

A DataInputStream can be "wrapped" around the BufferedInputStream to provide functionality for reading primitives and strings: DataInputStream dataInputStreamObject = new DataOutputStream( new BufferedInputStream( fileInputStreamObject ) );

Example: DataInputStream input = new DataInputStream(new BufferedInputStream( new FileInputStream("temp.dat") ) );

43 The BufferedOutputStream Class (Page 1)

"Wraps" around a FileOutputStream object to speed up output by reducing the number of disk writes

The whole block of data first is written into the RAM buffer; when the buffer is full, the block is written to disk

44 The BufferedOutputStream Class (Page 2) A subclass of FilterOutputStream It has no methods of its own--all are inherited from OutputStream Located in the java.io package import java.io.BufferedOutputStream;

45 The BufferedOutputStream Class (Page 3)

Format: BufferedOutputStream bufferedOutputStreamObject = new BufferedOutputStream( fileOutputStreamObject );

Example: BufferedOutputStream output = new BufferedOutputStream( new FileOutputStream( "temp.dat") );

46 The BufferedOutputStream Class (Page 4)

A DataOutputStream can be "wrapped" around the BufferedOutputStream to provide functionality to write primitives and strings: DataOutputStream dataOutputStreamObject = new DataOutputStream( new BufferedOutputStream( fileOutputStreamObject ) );

Example: DataOutputStream input = new DataOutputStream(new BufferedOutputStream( new

Page 4

EDxaatmaOpluet:putStream input = new DataOutputStream(new BufferedOutputStream( new

CST141--Binary I/OBuFfifleeOreudtOpuuttSpturteSatmre(a"mtemoupt.pduatt"=) )n)e;w BufferedOutputStream( new FileOutputStream(

"temp.dat") );

47 46

BufferedIOStream.java

(Page 1)

The BufferedOutputStream Class (Page 4)

48 BuAffDearteadOIuOtpSuttrSetaremam.jacvaan be "w(rPaapgpeed2")around the BufferedOutputStream to provide

49 BufuffnecrtieodnIaOlitSyttroeawmrit.ejapvraimitives(aPnadgestr3in)gs: DataOutputStream dataOutputStreamObject = new DataOutputStream( new

50 BuffBeurfefderIeOdSOturtepaumtS.tjraevama ( fileO(uPtpaugteSt4re)amObject ) );

51 BuEfxfaemrepdleI:OStream.java

(Page 5)

DataOutputStream input = new DataOutputStream(new BufferedOutputStream( new

52 BuffFeirleeOduItOpSuttSrteraemam.j(a"tveamp.dat(")P)ag);e 6)

4573 BThueffeOrbejdeIcOtISntpreuatSmt.rjeaavma Class(Pa(Pgeag1e) 1)

48

Bu"oWfbfjerearcpetssd"fIraOormSoutrtnhedeaaminFp.ijluaetvInsatpruetaSmtre(aPmagoebj2e)ct to give it the ability to read "serializable"

49 BuRfefaedres dpIriOmSittivresaman.djasvtarings as(Pwaegll e(c3o)ntains all the methods of class

50 BuDfafetarIendpIuOtSStrtereamam) .java

(Page 4)

Located in the java.io package

51 Buifmfeproerdt IjaOvSa.tiroe.Oambje.jcatIvnaputStre(aPma;ge 5)

524 BThueffeOrbejdeIcOtISntpreuatSmt.rjeaavma Class(Pa(Pgeag6e) 2)

53 ThFeorOmbajte:ctInputStream Class (Page 1) "oOWbbfjriejlaeecpItcsnstI"pfnruapotrumSottuSrtnethdraeemaainmOFpbiluoejetbIcnjsettprc)uet;ItaSnmtpruetaSmtreoabmjeOctbtjeocgt i=veniet wtheObajbeiclittIyntpourtSeatrdea"mse(rializable" RExeaamdsppler:imitives and strings as well (contains all the methods of class DOabtajeIcntpInuptSuttrSetarmea)m input = new ObjectInputStream( new FileInputStream( Loc"taetmedp.indatth"e) )ja; va.io package

55 ThiemOpobrjtejcatvOa.uiotp.OubtjSetcrteInapmutSCtlraesasm;(Page 1)

54

Th"oeWbjOreacbptjsse"tcoatrItohnuepnuodutaStptFurielteasOtmruetapCmulatSstsrea(mPaogbeje2ct)to give it the ability to write "serializable"

FWDLOooarbcfrtiimtaajleeetOaIsecnuttdp:IptnrpiunipumtuSttiShtttSriteverteerajeaasmavmamaOn).bidoojebspctjaerticcn)kt;gIansgpaeustSwterella(mcoOnbtajeincst

all the = new

methods of class ObjectInputStream(

Eimxapmoprtleja: va.io.ObjectOutputStream;

ObjectInputStream input = new ObjectInputStream( new FileInputStream(

56 The"Otebmjepc.dtOatu")tp);utStream Class (Page 2)

55 ThFeorOmbajte:ctOutputStream Class (Page 1) "oOWbbfjriejlaeecpOtcsstuO"ttouaprtutophtuuSenttSrodeturaatempaFumOiltebsOojtebrucejtetapc)mut;tOSutrtepaumtStorebajemctOtbojegcitve=itnethwe OabbijleitcytOtoutwpruitteSt"rseearmia(lizable" WExraitmesplper:imitives and strings as well (contains all the methods of class DOabtajeOcutOtpuutptSuttrSetarmea)m input = new ObjectOutputStream( new FileOutputStream( Loc"taetmedp.indatth"e) )ja; va.io package

57 ThiemrpeoartdjOabvaje.ioct.O()bjMecettOhuotdputStream;

56

ThAsetrmeOaebmthjeocdtOofuctlpasustSOtbrjeeactmInCpulatSstsrea(mPatghaet2re)ads a "serializable" object from the input

FMmFOooaubfrryismmjletetaaOchfitttrru::OosttuwptluopatauSCdttSrlatethrsaeesmaNcmOolatbsFojseobcujinetntc)dot;EORxuActepMputtiSotnrebaemcaOubsjeecwt h=ennethweOJbVjMecrteOsutotpreustStthreeaombj(ect, it

EoxbajmecptlIen:putStreamObject.readObject ();

EOxb"atjmeemcptlpOe.:udtaptu")tS)t;ream input = new ObjectOutputStream( new FileOutputStream(

SuffolkResident student = input.readObject();

57 The readObject() Method 58 The writeObject() Method

A method of class ObjectInputStream that reads a "serializable" object from the input sAtrmeaemthod of class ObjectInputString that writes a "serializable" object into the output Mstareyatmhrow a ClassNotFoundException because when the JVM restores the object, it mFoursmt afitr:st load the class into RAM FoobrjmecattO: utputStreamObject.writeObject( object ); EoxbajmecptlIen:putStreamObject.readObject ();

Page 5

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download