IO Examples

download IO Examples

of 58

Transcript of IO Examples

  • 7/24/2019 IO Examples

    1/58

    yet another insignifcant programming notes... | HOME

    TABLE OF CONTENTS (HIDE)1. File and Directory

    1.1 Classjava.io.File (re!"D# $%1.& Classjava.nio.fle.ath ("D# $%&. 'tream )O in 'tandard )O (java.io ac*age%

    +. ,yte!,ased )O - ,yte 'treams+.1 eading /rom an np0t'tream+.& riting to an O0tp0t'tream+.+ Opening - Closing )O 'treams+.2 Fl0shing the O0tp0t'tream+.3 mplementations o/ a4stract np0t'tream)O0tp0t'tream+.5 6ayered (or Chained% )O 'treams+.$ File )O ,yte!'treams ! Filenp0t'tream - FileO0tp0t'tream+.7 ,08ered )O ,yte!'treams ! ,08erednp0t'tream - ,08eredO0tp0t'tream+.9 Formatted Data!'treams: Datanp0t'tream - DataO0tp0t'tream+.1;

  • 7/24/2019 IO Examples

    2/58

    1.1 Class jaa.io.File (!re"#D$ %)

    ?he classjava.io.Filecan represent either a leor a directory. "D# 1.$ introd0ces a more

    versatilejava.nio.fle.athB =hich overcomes many limitations o/java.io.File.G

    >path stringis 0sed to locate a leor a directory. n/ort0natelyB path strings are system dependentB

    e.g.B Ic:JmyprojectJjavaJHello.javaI in indo=s or I)myproject)java)Hello.javaI in ni@)Mac.

    indo=s 0se 4ac*!slash KJKas the directory separatorL =hile ni@es)Mac 0se /or=ard!slash K)K. indo=s 0se semi!colon KLKaspath separatorto separate a list o/ pathsL =hile ni@es)Mac 0se

    colon K:K. indo=s 0se IJrJnI as line delimiter/or te@t fleL =hile ni@es 0se IJnI and Mac 0ses IJrI.

    ?he Ic:JI or IJI is called the root. indo=s s0pports m0ltiple rootsB each maps to a drive (e.g.B

    Ic:JIB Id:JI%. ni@es)Mac has a single root (IJI%.

    > path co0ld 4e absolute(4eginning /rom the root% or relative(=hich is relative to a re/erence directory%.

    'pecial notations I.I and I..I denote the c0rrent directory and the parent directoryB respectively.

    ?hejava.io.Fileclass maintains these system!dependent propertiesB /or yo0 to =rite programs that are

    porta4le:

    Directory Separator: in staticfelds File.separator(as 'tring% and File.separatorChar .

    ?hey /ailed to /ollo= the "ava naming convention /or constants adopted since "D# 1.&.G >s

    mentionedB indo=s 0se 4ac*slash KJKL =hile ni@es)Mac 0se /or=ard slash K)K. Path Separator : in staticfelds File.path'eparator(as 'tring%

    and File.path'eparatorChar. >s mentionedB indo=s 0se semi!colon KLK to separate a list o/

    pathsL =hile ni@es)Mac 0se colon K:K.

    o0 can constr0ct a File instance =ith a path string or B as /ollo=s. ?a*e note that the physical

    fle)directory may or may not e@ist. > fle 6 ta*es the /orm o/ fle:))...B

    e.g.B fle:)))d:)docs)programming)java)test.html.

    p04lic File('tringpathString%

    p04lic File('tringparentB 'tring child%

    p04lic File(FileparentB 'tring child%

    )) Constr0cts a File instance 4ased on the given path string.

    p04lic File( uri%)) Constr0cts a File instance 4y converting /rom the given fle! Ifle:))....I

    For e@amplesB

    File fle ne= File(Iin.t@tI%L )) > fle relative to the c0rrent =or*ing directory

    File fle ne= File(Id:JJmyprojectJJjavaJJHello.javaI%L )) > fle =ith a4sol0te path

    File dir ne= File(Ic:JJtempI%L )) > directory

    For applications that yo0 intend to distri40te as "> flesB yo0 sho0ld 0se the 6class to re/erence the

    reso0rcesB as it can re/erence dis* fles as =ell as ">Ked fles B /or e@ampleB

    java.net.6 0rl this.getClass(%.geteso0rce(Iicon.pngI%L

    &eri'yin !roerties o' a File*Directory

    p04lic 4oolean e+ists(% )) ?ests i/ this fle)directory e@ists.

    p04lic long lent,(% )) et0rns the length o/ this fle.

    p04lic 4oolean isDirectory(% )) ?ests i/ this instance is a directory.

    p04lic 4oolean isFile(% )) ?ests i/ this instance is a fle.

    p04lic 4oolean can-ead(% )) ?ests i/ this fle is reada4le.

    p04lic 4oolean canrite(% )) ?ests i/ this fle is =rita4le.

    p04lic 4oolean delete(% )) Deletes this fle)directory.

    p04lic void deleteOnE+it(% )) Deletes this fle)directory =hen the program terminates.

    p04lic 4oolean rena/eTo(File dest% )) enames this fle.

    p04lic 4oolean /0dir(% )) Ma*es (Creates% this directory.

    List Directory

    For a directoryB yo0 can 0se the /ollo=ing methods to list its contents:

    p04lic 'tringG list(% )) 6ist the contents o/ this directory in a 'tring!array

  • 7/24/2019 IO Examples

    3/58

    p04lic FileG listFiles(% )) 6ist the contents o/ this directory in a File!array

    E+a/le?he /ollo=ing program rec0rsively lists the contents o/ a given directory (similar to ni@Ks Ils

    !rIcommand%.

    )) ec0rsively list the contents o/ a directory (ni@Ks Ils !rI command%.

    import java.io.FileL

    p04lic class ListDirectory-ec2sieN p04lic static void main('tringG args% N

    File dir ne= File(Id:JJmyprojectJJtestI%L )) Escape se0ence needed /or KJK

    listec0rsive(dir%L

    P

    p04lic static void listec0rsive(File dir% N

    i/ (dir.isDirectory(%% N

    FileG items dir.listFiles(%L

    /or (File item : items% N

    'ystem.o0t.println(item.get>4sol0teFile(%%L

    i/ (item.isDirectory(%% listec0rsive(item%L )) ec0rsive call

    P

    P

    PP

    (Adanced) List Directory 3it, Filter

    o0 can apply a flter to list(%and listFiles(%B to list only fles that meet a certain criteria.

    p04lic 'tringG list(FilenameFilter lter%

    p04lic FileG listFiles(FilenameFilter lter%

    p04lic FileG listFiles(FileFilter lter%

    ?he inter/acejava.io.FilenameFilterdeclares one a4stractmethod:

    p04lic 4oolean accet(File dirNameB 'tring leName%

    ?he list(%and listFiles(%methods does a call-bacto accept(%/or each o/ the fle)s04!directory

    prod0ced. o0 can program yo0r fltering criteria in accept(%. ?hose fles)s04!directories that res0lt in

    a /alseret0rn =ill 4e [email protected]+a/le: ?he /ollo=ing program lists only fles that meet a certain fltering criteria.

    )) 6ist fles that end =ith I.javaI

    import java.io.FileL

    import java.io.FilenameFilterL

    p04lic class ListDirectoryit,FilterN

    p04lic static void main('tringG args% N

    File dir ne= File(I.I%L )) c0rrent =or*ing directory

    i/ (dir.isDirectory(%% N

    )) 6ist only fles that meet the fltering criteria

    )) programmed in accept(% method o/ FilenameFilter.

    'tringG fles dir.list(ne3 Filena/eFilter() 4

    25lic 5oolean accet(File dir6 Strin 7le) 4

    ret2rn 7le.endsit,(8.jaa8)9 :

    :%L )) an anonymo0s inner class as FilenameFilter

    /or ('tring fle : fles% N

    'ystem.o0t.println(fle%L

    P

    P

    P

    P

    1.; Class jaa.nio.7 le.!at,(#D$ %)

    ead IFile )O in "D# 1.$I.

    ;. Strea/ I*O in Standard I*O (jaa.io !ac0ae)

    rograms read inp0ts /rom data so0rces (e.g.B *ey4oardB fleB net=or*B memory 408erB or anotherprogram% and =rite o0tp0ts to data sin*s (e.g.B display consoleB fleB net=or*B memory 408erB or another

    http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html#jdk7iohttp://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html#jdk7io
  • 7/24/2019 IO Examples

    4/58

    program%. n "ava standard )OB inp0ts and o0tp0ts are handled 4y the so!called streams. > streamis a

    se0ential and contig0o0s one!=ay Qo= o/ data (j0st li*e =ater or oil Qo=s thro0gh the pipe%. t is

    important to mention that "ava does not di8erentiate 4et=een the vario0s types o/ data so0rces or sin*s

    (e.g.B fle or net=or*% in stream )O. ?hey are all treated as a se0ential Qo= o/ data. np0t and o0tp0t

    streams can 4e esta4lished /rom)to any data so0rce)sin*B s0ch as flesB net=or*B *ey4oard)console or

    another program. ?he "ava program receives data /rom a so0rce 4y opening an inp0t streamB and sends

    data to a sin* 4y opening an o0tp0t stream. >ll "ava )O streams are one!=ay (e@cept

    the andom>ccessFileB =hich =ill 4e disc0ssed later%. / yo0r program needs to per/orm 4oth inp0t

    and o0tp0tB yo0 have to open t=o streams ! an inp0t stream and an o0tp0t stream.

    'tream )O operations involve three steps:

    1. Openan inp0t)o0tp0t stream associated =ith a physical device (e.g.B fleB net=or*B

    console)*ey4oard%B 4y constr0cting an appropriate )O stream instance.

    &. !ead/rom the opened inp0t stream 0ntil Iend!o/!streamI enco0nteredB or "riteto the opened

    o0tp0t stream (and optionally Q0sh the 408ered o0tp0t%.

    +. #losethe inp0t)o0tp0t stream.

    "avaKs )O operations is more complicated than C)CRR to s0pport internationaliAation (i17n%. "ava

    internally stores characters (chartype% in 15!4it C'!& character set. ,0t the e@ternal data so0rce)sin*co0ld store characters in other character set (e.g.B '!>'CB 'O!7739!@B ?F!7B ?F!15B and many

    others%B in f@ed length o/ 7!4it or 15!4itB or in varia4le length o/ 1 to 2 4ytes. ead ICharacter 'ets and

    Encoding 'chemesIG. >s a conse0enceB "ava needs to di8erentiate 4et=een 4yte!4ased )O /or

    processing ra" bytesor binary dataB and character!4ased )O /or processing textsmade 0p o/ characters.

  • 7/24/2019 IO Examples

    5/58

    ,yte streams are 0sed to read)=rite ra" bytesserially /rom)to an e@ternal device. >ll the 4yte streams

    are derived /rom the a4stracts0perclasses np0t'treamand O0tp0t'treamB as ill0strated in the

    class diagram.

  • 7/24/2019 IO Examples

    6/58

    p04lic void a4stract void 3rite(int unsigned%yte% thro=s OE@ception

    'imilar to the read(%B t=o variations o/ the =rite(%method to =rite a 4loc* o/ 4ytes /rom a 4yte!array

    are implemented:

    p04lic void 3rite(4yteG bytesB int o$setB int length% thro=s OE@ception

    )) rite IlengthI n0m4er o/ 4ytesB /rom the bytesarray starting /rom o8set o/ index.

    p04lic void 3rite(4yteG bytes% thro=s OE@ception)) 'ame as =rite(bytesB ;B bytes.length%

    0tomatically closes all opened reso0rce in try (...%.

    Fl2s,in t,e O2t2tStrea/

    n additionB the O0tp0t'treamprovides a Q0sh(%method to Q0sh the remaining 4ytes /rom the o0tp0t

    408er.

    p04lic void ?2s,(% thro=s OE@ception )) Fl0sh the o0tp0t

  • 7/24/2019 IO Examples

    7/58

    a,08erednp0t'treamto a Filenp0t'tream/or 408ered inp0tB and stac* a Datanp0t'treamin

    /ront /or /ormatted data inp0t (0sing primitives s0ch as intB do04le%B as ill0strated in the /ollo=ing

    diagrams.

  • 7/24/2019 IO Examples

    8/58

    )) rint fle length

    File 7leIn ne3 File(inFileStr)9

    'ystem.o0t.println(IFile siAe is I R 7leIn.lent,() R I 4ytesI%L

    try N

    in ne3 FileIn2tStrea/(inFileStr)L

    o2t ne3 FileO2t2tStrea/(o2tFileStr)9

    start?ime 'ystem.nano?ime(%L

    int 4yteeadL

    )) ead a ra= 4yteB ret0rns an int o/ ; to &33.

    =hile ((5yte-ead in.read()% !1% N

    )) rite the least!signifcant 4yte o/ intB drop the 0pper + 4ytes

    o2t.3rite(5yte-ead)9

    P

    elapsed?ime 'ystem.nano?ime(% ! start?imeL

    'ystem.o0t.println(IElapsed ?ime is I R (elapsed?ime ) 1;;;;;;.;% R I msecI%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P fnally N )) al=ays close the )O streams

    try N i/ (in n0ll% in.close()L

    i/ (o0t n0ll% o2t.close()L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    P

    P

    P

    File siAe is 21$233 4ytes

    Elapsed ?ime is +$71.3;;371 msec

    ?his e@ample copies a fle 4y reading a 4yte /rom the inp0t fle and =riting it to the o0tp0t fle. t

    0ses Filenp0t'treamand FileO0tp0t'treamdirectly =itho0t 408ering. s mentionedB "D# 1.$ introd0ces a ne= try!=ith!reso0rces synta@B =hich a0tomatically closes all the

    reso0rces openedB a/ter tryor catch. For e@ampleB the a4ove e@ample can 4e re!=ritten in a m0ch

    neater manner as /ollo=:

    import java.io.SL

    p04lic class FileCoyNoB2er#D$%N

    p04lic static void main('tringG args% N

    'tring inFile'tr Itest!in.jpgIL

    'tring o0tFile'tr Itest!o0t.jpgIL

    long start?imeB elapsed?imeL )) /or speed 4enchmar*ing

    )) Chec* fle length

    File flen ne= File(inFile'tr%L

    'ystem.o0t.println(IFile siAe is I R flen.length(% R I 4ytesI%L

    )) Itry!=ith!reso0rcesI a0tomatically closes all opened reso0rces.

    try (FileIn2tStrea/ in ne3 FileIn2tStrea/(inFileStr)9

    FileO2t2tStrea/ o2t ne3 FileO2t2tStrea/(o2tFileStr)% N

    start?ime 'ystem.nano?ime(%L

  • 7/24/2019 IO Examples

    9/58

    int 4yteeadL

    )) ead a ra= 4yteB ret0rns an int o/ ; to &33.

    =hile ((5yte-ead in.read()% !1% N

    )) rite the least!signifcant 4yte o/ intB drop the 0pper + 4ytes

    o2t.3rite(5yte-ead)L

    P

    elapsed?ime 'ystem.nano?ime(% ! start?imeL 'ystem.o0t.println(IElapsed ?ime is I R (elapsed?ime ) 1;;;;;;.;% R I msecI%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    P

    P

    E+a/le ;Copying a fle =ith a rogrammer!Managed ,08er.

    import java.io.SL

    p04lic class FileCoyserB2er N )) re!"D# $

    p04lic static void main('tringG args% N

    'tring inFile'tr Itest!in.jpgIL

    'tring o0tFile'tr Itest!o0t.jpgIL

    Filenp0t'tream in n0llL

    FileO0tp0t'tream o0t n0llL

    long start?imeB elapsed?imeL )) /or speed 4enchmar*ing

    )) Chec* fle length

    File flen ne= File(inFile'tr%L

    'ystem.o0t.println(IFile siAe is I R flen.length(% R I 4ytesI%L

    try N

    in ne= Filenp0t'tream(inFile'tr%L

    o0t ne= FileO0tp0t'tream(o0tFile'tr%L

    start?ime 'ystem.nano?ime(%L

    5yteG 5yteB2' ne3 5yte>G9 )) 2# 4yte!408er

    int n0m,yteseadL =hile ((n0m,ytesead in.read(5yteB2') % !1% N

    o2t.3rite(5yteB2'6 6 n2/Bytes-ead)L

    P

    elapsed?ime 'ystem.nano?ime(% ! start?imeL

    'ystem.o0t.println(IElapsed ?ime is I R (elapsed?ime ) 1;;;;;;.;% R I msecI%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P fnally N )) al=ays close the streams

    try N

    i/ (in n0ll% in.close(%L

    i/ (o0t n0ll% o0t.close(%L

    P catch (OE@ception e@% N [email protected]'tac*?race(%L P

    P

    PP

    File siAe is 21$233 4ytes

    Elapsed ?ime is &.9+79&1 msec

    ?his e@ample again 0ses Filenp0t'treamand FileO0tp0t'treamdirectly. Ho=everB instead o/

    reading)=riting one 4yte at a timeB it reads)=rites a 2#, 4loc*. ?his program too* only + millisecond ! a

    more than 1;;; times speed!0p compared =ith the previo0s e@ample.

    6arger 408er siAeB 0p to a certain limitB generally improves the )O per/ormance. Ho=everB there is a

    trade!o8 4et=een speed!0p the the memory 0sage. For fle copyingB a large 408er is certainly

    recommended. ,0t /or reading j0st a /e= 4ytes /rom a fleB large 408er simply =astes the memory.

    re!=rite the program 0sing "D# 1.$B and try on vario0s 408er siAe on a m0ch 4igger fle o/ &5M,.

  • 7/24/2019 IO Examples

    10/58

    import java.io.SL

    p04lic class FileCoyserB2erLoo#D$%N

    p04lic static void main('tringG args% N

    'tring inFile'tr Itest!in.jpgIL

    'tring o0tFile'tr Itest!o0t.jpgIL

    long start?imeB elapsed?imeL )) /or speed 4enchmar*ing

    )) Chec* fle length

    File flen ne= File(inFile'tr%L

    'ystem.o0t.println(IFile siAe is I R flen.length(% R I 4ytesI%L

    intG 40/'iAe#, N1B &B 2B 7B 15B +&B 52B &35B 1;&2PL )) in #,

    int 40/'iAeL )) in 4ytes

    /or (int r0n ;L r0n T 40/'iAe#,.lengthL RRr0n% N

    40/'iAe 40/'iAe#,r0nG S 1;&2L

    try (Filenp0t'tream in ne= Filenp0t'tream(inFile'tr%L

    FileO0tp0t'tream o0t ne= FileO0tp0t'tream(o0tFile'tr%% N

    start?ime 'ystem.nano?ime(%L

    4yteG 4yte,0/ ne= 4yte40/'iAeGL int n0m,yteseadL

    =hile ((n0m,ytesead in.read(4yte,0/%% !1% N

    o0t.=rite(4yte,0/B ;B n0m,ytesead%L

    P

    elapsed?ime 'ystem.nano?ime(% ! start?imeL

    'ystem.o0t.print/(IU2d#,: U5.&/msecUnIB 40/'iAe#,r0nGB (elapsed?ime ) 1;;;;;;.;%%L

    ))'ystem.o0t.println(IElapsed ?ime is I R (elapsed?ime ) 1;;;;;;.;% R I msecI%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    P

    P

    P

    File siAe is &5&25;&5 4ytes &5 M,G 1#,: 3$+.32msec

    ,: +15.2+msec

    2#,: 1$7.2$msec

    7#,: 115.+&msec

    15#,: 73.51msec

    +,: 53.9&msec

    52#,: @%.1/sec

    &35#,: 5+.+7msec

    1;&2#,: 97.7$msec

    ncreasing 408er siAe helps only 0p to a certain pointV

    E+a/le

  • 7/24/2019 IO Examples

    11/58

    o2t ne3 B2eredO2t2tStrea/(ne3 FileO2t2tStrea/(o2tFileStr))9

    start?ime 'ystem.nano?ime(%L

    int 4yteeadL

    =hile ((4yteead in.read()% !1% N )) ead 4yte!4y!4yte /rom 408er

    o2t.3rite(5yte-ead)L

    P

    elapsed?ime 'ystem.nano?ime(% ! start?imeL 'ystem.o0t.println(IElapsed ?ime is I R (elapsed?ime ) 1;;;;;;.;% R I msecI%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P fnally N )) al=ays close the streams

    try N

    i/ (in n0ll% in.close(%L

    i/ (o0t n0ll% o0t.close(%L

    P catch (OE@ception e@% N [email protected]'tac*?race(%L P

    P

    P

    P

    File siAe is 21$233 4ytes

    Elapsed ?ime is 51.7+2932 msec

    n this e@ampleB chain

    the Filenp0t'tream=ith ,08erednp0t'treamB FileO0tp0t'tream=ith ,08eredO0tp0t'trea

    mB and read)=rite 4yte!4y!4yte. ?he "E decides on the 408er siAe. ?he program too* 5& millisecondsB

    a4o0t 5; times speed!0p compared =ith e@ample 1B 40t slo=er than the programmer!managed 408er.

    ?he "D# 1.$ version o/ the a4ove e@ample is as /ollo=s:

    import java.io.SL

    p04lic class FileCopy,08ered'tream"D#$ N

    p04lic static void main('tringG args% N

    'tring inFile'tr Itest!in.jpgIL

    'tring o0tFile'tr Itest!o0t.jpgIL

    long start?imeB elapsed?imeL )) /or speed 4enchmar*ing

    )) Chec* fle length

    File flen ne= File(inFile'tr%L

    'ystem.o0t.println(IFile siAe is I R flen.length(% R I 4ytesI%L

    try (B2eredIn2tStrea/ in ne3 B2eredIn2tStrea/(ne3 FileIn2tStrea/(inFileStr))9

    B2eredO2t2tStrea/ o2t ne3 B2eredO2t2tStrea/(ne3

    FileO2t2tStrea/(o2tFileStr)))N

    start?ime 'ystem.nano?ime(%L

    int 4yteeadL

    =hile ((4yteead in.read(%% !1% N

    o0t.=rite(4yteead%L P

    elapsed?ime 'ystem.nano?ime(% ! start?imeL

    'ystem.o0t.println(IElapsed ?ime is I R (elapsed?ime ) 1;;;;;;.;% R I msecI%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    P

    P

  • 7/24/2019 IO Examples

    12/58

    Datanp0t'tream in ne= Datanp0t'tream(

    ne= ,08erednp0t'tream(

    ne= Filenp0t'tream(Iin.datI%%%L

    Datanp0t'treamimplements Datanp0tinter/aceB =hich provides methods to read /ormatted

    primitive data and 'tringB s0ch as:)) 7 rimitives

    p04lic fnal int readInt(% thro=s OE@cpetionL )) ead 2 4ytes and convert into int

    p04lic fnal do04le readDo25e(% thro=s OE@cpetionL )) ead 7 4ytes and convert into do04le

    p04lic fnal 4yte readByte(% thro=s OE@cpetionL

    p04lic fnal char readC,ar(% thro=s OE@cpetionL

    p04lic fnal short readS,ort(% thro=s OE@cpetionL

    p04lic fnal long readLon(% thro=s OE@cpetionL

    p04lic fnal 4oolean readBoolean(% thro=s OE@cpetionL )) ead 1 4yte. Convert to /alse i/ Aero

    p04lic fnal Qoat readFloat(% thro=s OE@cpetionL

    p04lic fnal int readnsinedByte (% thro=s OE@cpetionL )) ead 1 4yte in ;B &33G 0pcast to int

    p04lic fnal int readnsinedS,ort (% thro=s OE@cpetionL )) ead & 4ytes in ;B 533+3GB same as charB 0pcast

    to int

    p04lic fnal void readF2lly(4yteG bB int o$B int len% thro=s OE@ceptionL

    p04lic fnal void readF2lly(4yteG b% thro=s OE@ceptionL

    )) 'trings

    p04lic fnal 'tring readLine(% thro=s OE@ceptionL

    )) ead a line (0ntil ne=line%B convert each 4yte into a char ! no 0nicode s0pport.

    p04lic fnal 'tring readTF(% thro=s OE@ceptionL

    )) read a ?F!encoded string =ith frst t=o 4ytes indicating its ?F 4ytes length

    p04lic fnal int s0iBytes(int n% )) '*ip a n0m4er o/ 4ytes

    'imilarlyB yo0 can stac* the DataO0tp0t'treamas /ollo=s:

    DataO0tp0t'tream o0t ne= DataO0tp0t'tream(

    ne= ,08eredO0tp0t'tream(

    ne= FileO0tp0t'tream(Io0t.datI%%%L

    DataO0tp0t'treamimplements DataO0tp0tinter/aceB =hich provides methods to =rite /ormatted

    primitive data and 'tring. For e@amplesB

    )) 7 primitive types

    p04lic fnal void 3riteInt(int i% thro=s OE@cpetionL )) rite the int as 2 4ytes

    p04lic fnal void 3riteFloat(Qoat f% thro=s OE@cpetionL

    p04lic fnal void 3riteDo25e(do04le d% thro=s OE@cpetionL )) rite the do04le as 7 4ytes

    p04lic fnal void 3riteByte(int b% thro=s OE@cpetionL )) least!signifcant 4yte

    p04lic fnal void 3riteS,ort(int s% thro=s OE@cpetionL )) t=o lo=er 4ytes

    p04lic fnal void 3riteLon(long l% thro=s OE@cpetionL

    p04lic fnal void 3riteBoolean(4oolean b% thro=s OE@cpetionLp04lic fnal void 3riteC,ar(int i% thro=s OE@cpetionL

    )) 'tring

    p04lic fnal void 3riteBytes('tring str% thro=s OE@cpetionL

    )) least!signifcant 4yte o/ each char

    p04lic fnal void 3riteC,ars('tring str% thro=s OE@cpetionL

    )) rite 'tring as C'!& 15!4it charB ,ig!endian (4ig 4yte frst%

    p04lic fnal void 3riteTF('tring str% thro=s OE@ceptionL

    )) rite 'tring as ?FB =ith frst t=o 4ytes indicating ?F 4ytes length

    p04lic fnal void 3rite(4yteG bB int o$B int len% thro=s OE@ception

    p04lic fnal void 3rite(4yteG b% thro=s OE@ception

    p04lic fnal void 3rite(int b% thro=s OE@ception )) rite the least!signifcant 4yte

  • 7/24/2019 IO Examples

    13/58

    E@ample: ?he /ollo=ing program =rites some primitives to a dis* fle. t then reads the ra= 4ytes to

    chec* ho= the primitives =ere stored. FinallyB it reads the data as primitives.

    import java.io.SL

    p04lic class ?estDataO'tream N

    p04lic static void main('tringG args% N

    'tring flename Idata!o0t.datIL

    'tring message IHiBIL

    )) rite primitives to an o0tp0t fle

    try (DataO0tp0t'tream o0t

    ne= DataO0tp0t'tream(

    ne= ,08eredO0tp0t'tream(

    ne= FileO0tp0t'tream(flename%%%% N

    o0t.=rite,yte(1&$%L

    o0t.=rite'hort(;@FFFF%L )) !1

    o0t.=ritent(;@>,CD%L

    o0t.=rite6ong(;@1&+2W35$7%L )) "D# $ synta@

    o0t.=riteFloat(11.&&/%L

    o0t.=riteDo04le(33.55%L

    o0t.=rite,oolean(tr0e%L

    o0t.=rite,oolean(/alse%L

    /or (int i ;L i T message.length(%L RRi% N

    o0t.=riteChar(message.char>t(i%%L

    P

    o0t.=riteChars(message%L

    o0t.=rite,ytes(message%L

    o0t.Q0sh(%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    )) ead ra= 4ytes and print in He@

    try (,08erednp0t'tream in

    ne= ,08erednp0t'tream(

    ne= Filenp0t'tream(flename%%% N

    int in,yteL

    =hile ((in,yte in.read(%% !1% N

    'ystem.o0t.print/(IU;&X IB in,yte%L )) rint He@ codes

    P

    'ystem.o0t.print/(IUnUnI%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    )) ead primitives try (Datanp0t'tream in

    ne= Datanp0t'tream(

    ne= ,08erednp0t'tream(

    ne= Filenp0t'tream(flename%%%% N

    'ystem.o0t.println(I4yte: I R in.read,yte(%%L

    'ystem.o0t.println(Ishort: I R in.read'hort(%%L

    'ystem.o0t.println(Iint: I R in.readnt(%%L

    'ystem.o0t.println(Ilong: I R in.read6ong(%%L

    'ystem.o0t.println(IQoat: I R in.readFloat(%%L

    'ystem.o0t.println(Ido04le: I R in.readDo04le(%%L

    'ystem.o0t.println(I4oolean: I R in.read,oolean(%%L

    'ystem.o0t.println(I4oolean: I R in.read,oolean(%%L

    'ystem.o0t.print(Ichar: I%L /or (int i ;L i T message.length(%L RRi% N

  • 7/24/2019 IO Examples

    14/58

    'ystem.o0t.print(in.readChar(%%L

    P

    'ystem.o0t.println(%L

    'ystem.o0t.print(Ichars: I%L

    /or (int i ;L i T message.length(%L RRi% N

    'ystem.o0t.print(in.readChar(%%L P

    'ystem.o0t.println(%L

    'ystem.o0t.print(I4ytes: I%L

    /or (int i ;L i T message.length(%L RRi% N

    'ystem.o0t.print((char%in.read,yte(%%L

    P

    'ystem.o0t.println(%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    P

    P

    $F FF FF ;; ;; >, CD ;; ;; ;; ;; ;; ;F 2& +F4yte short int long

    21 ++ 73 1F 2; 2, D2 $> E1 2$ >E 12

    Qoat do04le

    ;1 ;;

    4oolean 4oolean

    ;; 27 ;; 59 ;; &C 5; >7 39 $D ;; &1

    H i B

    ;; 27 ;; 59 ;; &C 5; >7 39 $D ;; &1

    H i B

    27 59 &C >7 $D &1

    lo= 4yte o/ the char onlyG

    4yte: 1&$

    short: !1int: 2+971

    long: +;3219795

    Qoat: 11.&&

    do04le: 33.55

    4oolean: tr0e

    4oolean: /alse

    char: HiB

    chars: HiB

    4ytes: HiBVP

    ?he data stored in the dis* are e@actly in the same /orm as in the "ava program internally (e.g.B C'!& /or

    characters%. ?he 4yte!order is 4ig!endian (4ig 4yte frstB or most signifcant 4yte in lo=est address%.

  • 7/24/2019 IO Examples

    15/58

    "ava internally stores characters (chartype% in 15!4it C'!& character set. ,0t the e@ternal data

    so0rce)sin* co0ld store characters in other character set (e.g.B '!>'CB 'O!7739!@B ?F!7B ?F!15B and

    many others%B in f@ed length o/ 7!4it or 15!4itB or in varia4le length o/ 1 to 2 4ytes. ead ICharacter 'ets

    and Encoding 'chemesIG. HenceB "ava has to di8erentiate 4et=een 4yte!4ased )O /or processing 7!4it

    ra= 4ytesB and character!4ased )O /or processing te@ts. ?he character streams needs

    to translate4et=een the character set 0sed 4y e@ternal )O devices and "ava internal C'!& /ormat. For

    e@ampleB the character KK is stored as I5; >7I in C'!& ("ava internal%B IE5 7& >7I in ?F7B IC2 F>Iin Y,#)Y,&+1&B and I,1 $>I in ,Y3. / this character is to 4e =ritten to a fle 0ses ?F!7B the character

    stream needs to translate I5; >7I to IE5 7& >7I. ?he reserve ta*es place in a reading operation.

    ?he 4yte)character streams re/er to the 0nit o/ operation =ithin the "ava programsB =hich does not

    necessary correspond to the amo0nt o/ data trans/erred /rom)to the e@ternal )O devices. ?his is 4eca0se

    some charsets 0se f@ed!length o/ 7!4it (e.g.B '!>'CB 'O!7739!1% or 15!4it (e.g.B C'!15%B =hile some

    0se varia4le!length o/ 1!2 4ytes (e.g.B ?F!7B ?F!15B ?F!15!,EB ?F!15!6EB Y,#B ,Y3%. hen a

    character stream is 0sed to read an 7!4it >'C fleB an 7!4it data is read /rom the fle and p0t into the 15!

    4it charlocation o/ the "ava program.

    >.1 A5stract s2erclass -eader and riter

    Other than the 0nit o/ operation and charset conversion (=hich is e@tremely comple@%B character!4ased

    )O is almost identical to 4yte!4ased )O. nstead o/ np0t'treamand O0tp0t'treamB =e

    0se eaderand riter/or character!4ased )O.

    ?he a4stracts0perclass eaderoperates on char. t declares an a4stractmethod read(%to read one

    character /rom the inp0t so0rce. read(%ret0rns the character as an int4et=een ; to 533+3 (a charin

    "ava can 4e treated as an 0nsigned 15!4it integer%L or !1 i/ end!o/!stream is detectedL or thro=s

    an OE@ceptioni/ )O error occ0rs. ?here are also t=o variations o/ read(%to read a 4loc* o/ characters

    into char!array.

    p04lic a4stract int read(% thro=s OE@ception

    p04lic int read(charG charsB int o$setB int length% thro=s OE@ception

    p04lic int read(charG chars% thro=s OE@ception

    ?he a4stracts0perclass riterdeclares an a4stractmethod =rite(%B =hich =rites a character to the

    o0tp0t sin*. ?he lo=er & 4ytes o/ the intarg0ment is =ritten o0tL =hile the 0pper & 4ytes are discarded.

    p04lic void a4stract void 3rite(int a#har% thro=s OE@ceptionp04lic void 3rite(charG charsB int o$setB int length% thro=s OE@ception

    http://www3.ntu.edu.sg/home/ehchua/programming/java/DataRepresentation.html#charencodinghttp://www3.ntu.edu.sg/home/ehchua/programming/java/DataRepresentation.html#charencodinghttp://www3.ntu.edu.sg/home/ehchua/programming/java/DataRepresentation.html#charencodinghttp://www3.ntu.edu.sg/home/ehchua/programming/java/DataRepresentation.html#charencoding
  • 7/24/2019 IO Examples

    16/58

    p04lic void 3rite(charG chars% thro=s OE@ception

    >.; File I*O C,aracter"Strea/s " File-eader = Fileriter

    Fileeaderand Fileriterare concrete implementations to

    the a4stracts0perclasses eaderand riterB to s0pport )O /rom dis*

    fles. Fileeader)Fileriterass0mes that the default character encoding(charset% is 0sed /or the dis*

    fle. ?he de/a0lt charset is *ept in the "ZMKs system property Ifle.encodingI. o0 can get the de/a0lt

    charset

    via staticmethodjava.nio.charset.Charset.de/a0ltCharset(%or 'ystem.getroperty(Ifle.enco

    dingI%. t is pro4a4le sa/e to 0se Fileeader)Fileriter/or >'C te@tsB provided that the de/a0lt

    charset is compati4le to >'C (s0ch as '!>'CB 'O!7739!@B ?F!7B and many othersB 40t .> C,aracter Set (or C,arset) " !ac0ae jaa.nio.c,arset (#D$1.>)

    "D# 1.2 provides a ne= pac*agejava.nio.charsetas part o/ 'CB 'O!7739!@B ?F!7B ?F!15B ?F!15,EB ?F!156EB

    and etc.%

    ?he main classjava.nio.charset.Charsetprovides staticmethods /or testing =hether a partic0lar

    charset is s0pportedB locating charset instances 4y nameB and listing all the availa4le charsets and thede/a0lt charset.

  • 7/24/2019 IO Examples

    17/58

    p04lic static 'ortedMapT'tringBCharset[ aaila5leC,arsets(% )) lists all the availa4le charsets

    p04lic static Charset de'a2ltC,arset(% )) et0rns the de/a0lt charset

    p04lic static Charset 'orNa/e('tring charset

  • 7/24/2019 IO Examples

    18/58

    I?F!15,EIB I?F!156EIB IY,#IB I,Y3IPL

    'tring message IHiBIL )) nicode message to 4e encoded

    )) rint C'!& in he@ codes

    'ystem.o0t.print/(IU1;s: IB IC'!&I%L

    /or (int i ;L i T message.length(%L RRi% N

    'ystem.o0t.print/(IU;2X IB (int%message.char>t(i%%L P

    'ystem.o0t.println(%L

    /or ('tring charset'C: 27 59 &C +F +F &1 7!4it f@ed!lengthG

    H i B V V

    'O!7739!1: 27 59 &C +F +F &1 7!4it f@ed!lengthG

    H i B V V

    ?F!7: 27 59 &C E5 7& >7 E3 >3 ,D &1 1!2 4ytes varia4le!lengthG

    H i B

    ?F!15: FE FF ;; 27 ;; 59 ;; &C 5; >7 39 $D ;; &1 &!2 4ytes varia4le!lengthG

    ,OM H i B

    ,yte!Order!Mar* indicates ,ig!EndianG ?F!15,E: ;; 27 ;; 59 ;; &C 5; >7 39 $D ;; &1 &!2 4ytes varia4le!lengthG

    H i B

    ?F!156E: 27 ;; 59 ;; &C ;; >7 5; $D 39 &1 ;; &!2 4ytes varia4le!lengthG

    H i B

    Y,#: 27 59 &C C2 F> ,> C+ &1 1!& 4ytes varia4le!lengthG

    H i B

    ,ig3: 27 59 &C ,1 $> >5 5E &1 1!& 4ytes varia4le!lengthG

    H i B

    E+a/le ?he /ollo=ing e@ample tries o0t the encoding)decoding on Char,08erand ,yte,08er.

    ,08ers =ill 4e disc0ssed later 0nder

  • 7/24/2019 IO Examples

    19/58

    Charset charset Charset./or7 39 $D ;; &1

    ?F!7: 27 59 &C E5 7& >7 E3 >3 ,D &1

    C'!&: KHK;;27G KiK;;59G KBK;;&CG KK5;>7G KK39$DG KK;;&1G

    >.@ Te+t File I*O " In2tStrea/-eader and O2t2tStrea/riter

    >s mentionedB "ava internally stores characters (chartype% in 15!4it C'!& character set. ,0t the

    e@ternal data so0rce)sin* co0ld store characters in other character set (e.g.B '!>'CB 'O!7739!@B ?F!7B

    ?F!15B and many others%B in f@ed length o/ 7!4it or 15!4itB or in varia4le length o/ 1 to 2 4ytes.?he Fileeader)Fileriterintrod0ced earlier 0ses the de/a0lt charset /or decoding)encodingB res0lted

    in non!porta4le programs.

    ?o choose the charsetB yo0 need to

    0se np0t'treameaderand O0tp0t'treamriter. np0t'treameader and O0tp0t'treamri

    terare considered to 4e 4yte!to!character I4ridgeI streams.

    o0 can choose the character set in the np0t'treameaderKs constr0ctor:

    p04lic In2tStrea/-eader (np0t'tream in% )) se de/a0lt charset

    p04lic In2tStrea/-eader (np0t'tream inB 'tring charsetName% thro=s ns0pportedEncodingE@ception

    p04lic In2tStrea/-eader (np0t'tream inB Charset cs%

    o0 can list the availa4le charsets

    via staticmethodjava.nio.charset.Charset.availa4leCharsets(%. ?he commonly!

    0sed Charsetnames s0pported 4y "ava are:

    I'!>'CI: $!4it >'C (a*a 'O525!'%

    I'O!7739!1I: 6atin!1

    I?F!7I: Most commonly!0sed encoding scheme /or nicode

    I?F!15,EI: ,ig!endian (4ig 4yte frst% (4ig!endian is 0s0ally the de/a0lt%

    I?F!156EI: 6ittle!endian (little 4yte frst%

    I?F!15I: =ith a &!4yte ,OM (,yte!Order!Mar*% to speci/y the 4yte order. FE FF indicates 4ig!

    endianB FF FE indicates little!endian.

    >s the np0t'treameader)O0tp0t'treamriter o/ten needs to read)=rite in m0ltiple 4ytesB it is

    4est to =rap it =ith a ,08eredeader),08eredriter.

    E+a/le ?he /ollo=ing program =rites nicode te@ts to a dis* fle 0sing vario0s charsets /or fle

    encoding. t then reads the fle 4yte!4y!4yte (via a 4yte!4ased inp0t stream% to chec* the encodedcharacters in the vario0s charsets. FinallyB it reads the fle 0sing the character!4ased reader.

  • 7/24/2019 IO Examples

    20/58

    import java.io.SL

    )) rite te@ts to fle 0sing O0tp0t'treamriter speci/ying its charset encoding.

    )) ead 4yte!4y!4yte 0sing Filenp0t'tream.

    )) ead char!4y!char 0sing np0t'treameader speci/ying its charset encoding.

    p04lic class Te+tFileEncodin#D$%N

    p04lic static void main('tringG args% N

    'tring message IHiBIL )) =ith non!>'C chars )) "ava internally stores char in C'!&)?F!15

    )) rint the characters stored =ith He@ codes

    /or (int i ;L i T message.length(%L RRi% N

    char aChar message.char>t(i%L

    'ystem.o0t.print/(IUdGKUcK(U;2X% IB (iR1%B aCharB (int%aChar%L

    P

    'ystem.o0t.println(%L

    )) ?ry these charsets /or encoding te@t fle

    'tringG cs'trs 48TF"86 8TF"1BE86 8TF"1LE86 8TF"186 8KB;

  • 7/24/2019 IO Examples

    21/58

    P

    'ystem.o0t.println(%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    P

    PP

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%

    ?F!7: 27 59 &C E5 7& >7 E3 >3 ,D &1

    H i B

    ?F!15,E: ;; 27 ;; 59 ;; &C 5; >7 39 $D ;; &1

    H i B

    ?F!156E: 27 ;; 59 ;; &C ;; >7 5; $D 39 &1 ;;

    H i B

    ?F!15: FE FF ;; 27 ;; 59 ;; &C 5; >7 39 $D ;; &1

    ,OM H i B

    Y,&+1&: 27 59 &C C2 F> ,> C+ &1

    H i B

    Y,#: 27 59 &C C2 F> ,> C+ &1

    H i B

    ,Y3: 27 59 &C ,1 $> >5 5E &1

    H i B

    ?F7

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%

    nicode,ignmar*ed ?F!15,E =itho0t ,OMG

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%

    nicode6ittlenmar*ed F?!156E =itho0t ,OMG

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%

    ?F!15

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%

    ECWC< Y,&+1&G

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%

    Y,#

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%

    ,ig3

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%

    >s seen /rom the o0tp0tB the characters is encoded di8erently in di8erent charsets.

  • 7/24/2019 IO Examples

    22/58

    ?he 4yte!4asedjava.io.print'teams0pports convenient printing methods s0ch

    as print(%and println(% /or printing primitives and te@t string. rimitives are converted to their string

    representation /or printing. ?he print/(%and /ormat(%=ere introd0ced in "D# 1.3 /or /ormatting o0tp0t

    =ith /ormer specifers. print/(%and /ormat(%are identical.> rint'treamnever thro=s an OE@ception. nsteadB it sets an internal Qag =hich can 4e chec*ed via

    the chec*Error(%method. >rint'treamcan also 4e created to Q0sh the o0tp0t a0tomatically. ?hat isB

    the Q0sh(%method is a0tomatically invo*ed a/ter a 4yte array is =rittenB one o/ the println(% methods is

    invo*edB or a/ter a ne=line (KJnK% is =ritten.

    ?he standard o0tp0t and error streams ('ystem.o0tand 'ystem.err% 4elong to rint'tream.

    >ll characters printed 4y a rint'treamare converted into 4ytes 0sing the de/a0lt character encoding.

    ?he rintriterclass sho0ld 4e 0sed in sit0ations that re0ire =riting characters rather than 4ytes.

    ?he character!stream rintriteris similar to rint'treamB e@cept that it =rite in characters instead o/

    4ytes. ?he rintriteralso s0pports all the convenient printing

    methods print(%B println(%B print/(%and /ormat(%. t never thro=s an OE@ceptionand can optionally

    4e created to s0pport a0tomatic Q0shing.

    ?ODOG E@ample to sho= the di8erence 4et=een rint'treamand rintriter.. O5ject SerialiMation and O5ject Strea/s

    Data streams (Datanp0t'treamand DataO0tp0t'tream% allo= yo0 to read and =rite primitive data

    (s0ch as intB do04le% and 'tringB rather than individ0al 4ytes. O4ject streams

    (O4jectnp0t'treamand O4jectO0tp0t'tream% go one step /0rther to allo= yo0 to read and =rite

    entire o4jects (s0ch as DateB >rray6istor any c0stom o4jects%.

    O4ject serialiAation is the process o/ representing a Ipartic0lar state o/ an o4jectI in a serialiAed 4it!

    streamB so that the 4it stream can 4e =ritten o0t to an e@ternal device (s0ch as a dis* fle or net=or*%.

    ?he 4it!stream can later 4e re!constr0cted to recover the state o/ that o4ject. O4ject serialiAation is

    necessary to save a state o/ an o4ject into a dis* fle /or persistenceor sent the o4ject across the

    net=or* /or applications s0ch as e4 'ervicesB Distri40ted!o4ject applicationsB and emote Method

    nvocation (M%.n "avaB o4ject that re0ires to 4e serialiAed m0st

    implementjava.io.'erialiAa4leorjava.io.E@ternaliAa4leinter/ace. 'erialiAa4leinter/ace is

    an empty inter/ace (or tagged inter/ace% =ith nothing declared. ts p0rpose is simply to declare that

    partic0lar o4ject is serialiAa4le.

    .1 O5jectIn2tStrea/ = O5jectO2t2tStrea/

    ?he O4jectnp0t'treamand O4jectO0tp0t'tream can 4e 0sed to serialiAe an o4ject into a 4it!

    stream and trans/er it to)/rom an )O streamsB via these methods:

    p04lic fnal O4ject readO5ject(% thro=s OE@ceptionB Class

  • 7/24/2019 IO Examples

    23/58

    O4jectO0tp0t'tream o0t

    ne= O4jectO0tp0t'tream(

    ne= ,08eredO0tp0t'tream(

    ne= FileO0tp0t'tream(Io4ject.serI%%%L

    o0t.=riteO4ject(I?he c0rrent Date and ?ime is I%L )) =rite a 'tring o4ject

    o0t.=riteO4ject(ne= Date(%%L )) =rite a Date o4ject

    o0t.Q0sh(%L

    o0t.close(%L

    ?o read and re!constr0ct the o4ject 4ac* in a programB 0se the method readO4ject(%B =hich ret0rns

    anjava.lang.O4ject. Do=ncast the O4ject4ac* to its original type.

    O4jectnp0t'tream in

    ne= O4jectnp0t'tream(

    ne= ,08erednp0t'tream(

    ne= Filenp0t'tream(Io4ject.serI%%%L

    'tring str ('tring%in.readO4ject(%L

    Date d (Date%in.readO4ject(ne= Date(%%L )) do=ncastin.close(%L

    E+a/le O4ject serialiAation

    import java.io.SL

    p04lic class O4ject'erialiAation?est N

    p04lic static void main('tringG args% N

    'tring flename Io4ject.serIL

    int n0mO4js 3L

    )) rite o4jects

    try (O4jectO0tp0t'tream o0t

    ne= O4jectO0tp0t'tream(

    ne= ,08eredO0tp0t'tream(

    ne= FileO0tp0t'tream(flename%%%% N

    )) Create an array o/ 1; My'erialiAedO4jects =ith ascending n0m4ers

    My'erialiAedO4jectG o4js ne= My'erialiAedO4jectn0mO4jsGL

    /or (int i ;L i T n0mO4jsL RRi% N

    o4jsiG ne= My'erialiAedO4ject(;@>> R i%L )) 'tarting at >>

    P

    )) rite the o4jects to fleB one 4y one.

    /or (int i ;L i T n0mO4jsL RRi% N

    o0t.=riteO4ject(o4jsiG%L P

    )) rite the entire array in one go.

    o0t.=riteO4ject(o4js%L

    o0t.Q0sh(%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    )) ead ra=s 4ytes and print in He@

    try (,08erednp0t'tream in

    ne= ,08erednp0t'tream(

    ne= Filenp0t'tream(flename%%% N

    int in,yteL

    =hile ((in,yte in.read(%% !1% N

    'ystem.o0t.print/(IU;&X IB in,yte%L )) rint He@ codes

  • 7/24/2019 IO Examples

    24/58

    P

    'ystem.o0t.print/(IUnUnI%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    )) ead o4jects try (O4jectnp0t'tream in

    ne= O4jectnp0t'tream(

    ne= ,08erednp0t'tream(

    ne= Filenp0t'tream(flename%%%% N

    )) ead 4ac* the o4jectsB cast 4ac* to its original type.

    My'erialiAedO4ject o4jnL

    /or (int i ;L i T n0mO4jsL RRi% N

    o4jn (My'erialiAedO4ject%in.readO4ject(%L

    'ystem.o0t.println(o4jn.get

  • 7/24/2019 IO Examples

    25/58

    .; jaa.io.SerialiMa5le = E+ternaliMa5le Inter'aces

    hen yo0 create a class that might 4e serialiAedB the class m0st

    implementjava.io.'erialiAa4leinter/ace. ?he 'erialiAa4leinter/ace doesnKt declare any methods.

    Empty inter/aces s0ch as'erialiAa4leare *no=n as tagging interfaces. ?hey identi/y implementing

    classes as having certain propertiesB =itho0t re0iring those classes to act0ally implement any methods.

    Most o/ the core "ava classes implement 'erialiAa4leB s0ch as all the =rapper classesB collectionclassesB and Y classes. n /actB the only core "ava classes that do not implement 'erialiAa4leare ones

    that sho0ld not 4e serialiAed. >rrays o/ primitives or serialiAa4le o4jects are themselves serialiAa4le.arnin essae 8T,e serialiMation class does not declare a static 7nalserial&ersionID 7eld o' tye lon8 (Adanced)

    ?his =arning message is triggered 4eca0se yo0r class (s0ch asjava.s=ing."Frame% implements

    thejava.io.'erialiAa4le inter/ace. ?his inter/ace ena4les the o4ject to 4e =ritten o0t to an o0tp0t

    stream serially(via method =riteO4ject(%%L and read 4ac* into the program (via

    method readO4ject(%%. ?he serialiAation r0ntime 0ses a n0m4er (called serialZersionD% to ens0re

    that the o4ject read into the program (d0ring deserialiAation% is compati4le =ith the class defnitionB and

    not 4elonging to another version. t thro=s an nvalidClassE@ceptionother=ise.

    o0 have these options:

    1. 'imply ignore this =arning message. / a serialiAa4leclass does not e@plicitly declare

    a serialZersionD B then the serialiAation r0ntime =ill calc0late a

    de/a0lt serialZersionD val0e /or that class 4ased on vario0s aspects o/ the class.

    &. >dd a serialZersionD (ecommended%B e.g.

    private static fnal long serial&ersionID 16L )) verion 1

    +. '0ppress this partic0lar =arning via annotation \'0ppressarmomgs (in

    pac*agejava.lang% ("D# 1.3%:

    2. S2ressarnins(8serial8)

    p04lic class MyFrame e@tends "Frame N ...... P

    jaa.io.E+ternal iMa5le Inter'ace

    ?he 'erialiAa4lehas a s04!inter/ace called E@ternaliAa4leB =hich yo0 co0ld 0sed i/ yo0 =ant toc0stomiAe the =ay a class is serialiAed. 'ince E@ternaliAa4lee@tends 'erialiAa4leB it is also

    a'erialiAa4leand yo0 co0ld invo*e readO4ject(%and =riteO4ject(%.

    E@ternaliAa4ledeclares t=o a4stractmethods:

    void 3riteE+ternal(O4jectO0tp0t out% thro=s OE@ception

    void readE+ternal(O4jectnp0t in% thro=s OE@ceptionB Class

  • 7/24/2019 IO Examples

    26/58

    do04le%. ?he fle pointer is located at ; =hen the fle is opened. t advances a0tomatically /or every read

    and =rite operation 4y the n0m4er o/ 4ytes processed.

    n constr0cting a andom>ccessFileB yo0 can 0se Qags KrKor Kr=Kto indicate =hether the fle is Iread!

    onlyI or Iread!=riteI accessB e.g.B

    andom>ccessFile /1 ne= -ando/AccessFile(IflenameIB IrI%L

    andom>ccessFile /& ne= -ando/AccessFile(IflenameIB Ir=I%L

    ?he /ollo=ing methods are availa4le:

    p04lic void see0(longpos% thro=s OE@ceptionL)) ositions the fle pointer /or s04se0ent read)=rite operation.

    p04lic int s0iBytes(int num%ytes% thro=s OE@ceptionL

    )) Moves the fle pointer /or=ard 4y the specifed n0m4er o/ 4ytes.

    p04lic long etFile!ointer(% thro=s OE@ceptionL

    )) Yets the position o/ the c0rrent fle pointerB in 4ytesB /rom the 4eginning o/ the fle.

    p04lic long lent,(% thro=s OE@ceptionL

    )) et0rns the length o/ this fle.

    andom>ccessFiledoes not inherit /rom np0t'treamor O0tp0t'tream. Ho=everB it

    implements Datanp0tand DataO0tp0tinter/aces (similar

    to Datanp0t'treamand DataO0tp0t'tream%. ?here/oreB yo0 can 0se vario0s methods to read)=rite

    primitive types to the fleB e.g.B

    p04lic int readInt(% thro=s OE@ceptionL

    p04lic do04le readDo25le(% thro=s OE@ceptionL

    p04lic void 3riteInt(int i% thro=s OE@ceptionL

    p04lic void 3riteDo25le(do04le d% thro=s OE@ceptionL

    E+a/le ead and =rite records /rom a andom>ccessFile. (> st0dent fle consists o/ st0dent

    record o/ name ('tring% and id (int%%.

    E

  • 7/24/2019 IO Examples

    27/58

    ?he to*ens may then 4e converted into primitive val0es o/ di8erent types 0sing the

    vario0s ne@tX@@(%methods

    (ne@tnt(%B ne@t,yte(%B ne@t'hort(%B ne@t6ong(%B ne@tFloat(%B ne@tDo04le(%Bne@t,oolean(%B ne

    @t(%/or 'tringB and ne@t6ine(%/or an inp0t line%. o0 can also 0se the has

  • 7/24/2019 IO Examples

    28/58

    ?he ne@tX@@(%methods thro= np0tMismatchE@ceptioni/ the ne@t to*en does not match the type

    to 4e parsed.

    E+a/le ;o0 can easily modi/y the a4ove program to read the inp0ts /rom a te@t fleB instead o/

    *ey4oard ('ystem.in%.

    import java.0til.'cannerL

    import java.io.SL

    p04lic class TestScannerFileN

    p04lic static void main('tringG args% thro=s File

  • 7/24/2019 IO Examples

    29/58

    )) ]ero or more =hitespaceB /ollo=ed 4y KappleKB /ollo=ed 4y Aero or more =hitespace.

    in.0seDelimiter(IJJsSappleJJsSI%L

    )) ?he delimiter 4rea*s the inp0t into to*ens NIoneIB I&IB IredIB I4igIB I3.3IP.

    'ystem.o0t.println(in.ne@t(%%L

    'ystem.o0t.println(in.ne@tnt(%%L )) parses te@t into int

    'ystem.o0t.println(in.ne@t(%%L

    'ystem.o0t.println(in.ne@t(%%L 'ystem.o0t.println(in.ne@tDo04le(%%L )) parses te@t into do04le

    P

    P

    ?he reg0lar e@pression JsSappleJsSmatches Aero or more =hite spaces (JsS% /ollo=ed 4y IappleI

    /ollo=ed 4y Aero or more =hite spaces (JsS%. >n additional 4ac*slash (J% is needed to 0se a 4ac*slash (J%

    in "ava 'tringKs literal. ead Ieg0lar E@pressionI /or more details.-ee+e !attern atc,in

    o0 can 0se the /ollo=ing methods to fnd the ne@t occ0rrence o/ the specifed pattern 0sing reg0lar

    e@pressions:

    )) Find the ne@t occ0rrence o/ a patternB ignoring delimiters

    p04lic 'tring 7ndInLine(atternpattern%p04lic 'tring 7ndInLine('tringpattern%

    p04lic 'tring 7ndit,inHoriMon(atternpatternB int hori'on%

    p04lic 'tring 7ndit,inHoriMon('tringpatternB int hori'on%

    )) '*ips inp0t that matches the specifed patternB ignoring delimiters

    p04lic 'canner s0i(atternpattern%

    p04lic 'canner s0i('tringpattern%

    C,arset

    ,y de/a0ltB 'canner0ses the de/a0lt charset to read the character /rom the inp0t so0rce. o0 can

    as* 'cannerto read te@t fle =hich is encoded 0sing a partic0lar charsetB 4y providing the charset

    name.

    E+a/le >

    import java.0til.SL

    import java.io.SL

    p04lic class ?est'canner?e@tFile N

    p04lic static void main('tringG args% thro=s File'C chars

    )) Create a ?e@t fle in ?F!7

    )) Can also 0se /ormatter (see 4elo=%

    try (,08eredriter o0t

    ne= ,08eredriter(

    ne= O0tp0t'treamriter(

    ne= FileO0tp0t'tream(flename%B I?F!7I%%% N

    o0t.=rite(I1&+23 33.55JnI%L o0t.=rite(message%L

    o0t.Q0sh(%L

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    )) ead ra=s 4ytes and print in He@

    try (,08erednp0t'tream in

    ne= ,08erednp0t'tream(

    ne= Filenp0t'tream(flename%%% N

    int in,yteL

    =hile ((in,yte in.read(%% !1% N

    'ystem.o0t.print/(IU;&X IB in,yte%L )) rint He@ codes

    P 'ystem.o0t.println(%L

    http://www3.ntu.edu.sg/home/ehchua/programming/howto/Regexe.htmlhttp://www3.ntu.edu.sg/home/ehchua/programming/howto/Regexe.html
  • 7/24/2019 IO Examples

    30/58

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    )) Open a te@t fleB speci/ying the charset /or the fle encoding

    'canner in ne= 'canner(ne= File(flename%B I?F!7I%L

    'ystem.o0t.println(in.ne@tnt(%%L 'ystem.o0t.println(in.ne@tFloat(%%L

    in.ne@t6ine(%L )) Fl0sh a ne=line

    'ystem.o0t.println(in.ne@t6ine(%%L

    P

    P

    +1 +& ++ +2 +3 &; +3 +3 &E +5 +5 ;> 27 59 &C E5 7& >7 E3 >3 ,D &1 ;>

    1 & + 2 3 ' 3 3 . 5 5 6F H i B 6F ?F!7G

    1&+23

    33.55

    HiB

    .; For/atted"Te+t !rintin 3it, rint'() /et,od

    "D# 1.3 introd0ces C!li*e print/(%method (in classesjava.io.rint'teamandjava.io.rintriter% /or

    /ormatted!te@t printing.

    ?o =rite /ormatted!te@t to console ('ystem.o0tor 'ystem.err%B yo0 co0ld simply 0se the convenience

    methods 'ystem.o0t.print/(%or 'ystem.o0t./ormat(%. print/(%ta*es this synta@:

    p04lic rint'tream|rintriter rint'('tring formatSpecierB O4ject... args%

    p04lic rint'tream|rintriter rint'(6ocale localeB 'tring formatSpecierB O4ject... args%

    print/(%ta*es a varia4le n0m4er (Aero or more% o/ arg0ments (or varargs%. Zarargs =as introd0ced in "D#

    1.3 (that is the reason "ava cannot s0pport print/(%earlier%.

    print/(%can 4e called /rom 'ystem.o0tor 'ystem.err( =hich are rint'treams%. For e@ampleB

    'ystem.o0t.print/(IHello U2d U5.&/ UsB andUn Hello againUnIB 1&+B 3.3B IHelloI%L

    Hello 1&+ 3.3; HelloB and Hello again

    o0 can also 0se the 'ystem.o0t./ormat(%methodB =hich is identical to 'ystem.o0t.print/(%.For/at Seci7 ers

    > /ormat specifer 4egins =ith KUKand ends =ith a conversion!type character (e.g. IUdI/or

    integerB IU/I/or Qoatand do04le%B =ith optional parameters in 4et=eenB as /ollo=s:

    Uargument(position G)ag*s+G"idthG.precisionGconversion-type-character

    ?he optional argument(positionspecifes the position o/ the arg0ment in the arg0ment list. ?he

    frst arg0ment is I1^IB second arg0ment is I&^IB and so on. ?he optional "idthindicates the minim0m n0m4er o/ characters to 4e o0tp0t.

    ?he optionalprecisionrestricts the n0m4er o/ characters (or n0m4er o/ decimal places /or Qoat!point n0m4ers%.

    ?he mandatory conversion-type-characterindicates ho= the arg0ment sho0ld 4e /ormatted. For

    e@amples: K4KB K,K(4oolean%B KhKB KHK(he@ string%B KsKB K'K(string%B KcKB KCK(character%B KdK(decimal

    integer%B KoK(octal integer%B K@KB KXK(he@adecimal integer%B KeKB KEK(Qoat!point n0m4er in scientifc

    notation%B K/K(Qoating!point n0m4er%B KUK(percent sign%. ?he 0ppercase conversion code (e.g.B K'K%

    /ormats the te@ts in 0ppercase.

    Flag: K!K(le/t!j0stifed%B KRK(incl0de sign%B K K(incl0de leading space%B K;K(Aero!

    padded%B KBK(incl0de gro0ping separator%. K(K(negative val0e in parentheses%B K_K(alternative /orm%.

    ead "D# >java.0til.FormatterKs IFormat 'tring 'ynta@I /or details on /ormat specifers.E+a/les

    'ystem.o0t.print/(IU&^&d U+^&d U1^&dUnIB 1B 1&B 1&+B 1&+2%L

    1& 1&+ 1

    http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntaxhttp://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
  • 7/24/2019 IO Examples

    31/58

    'ystem.o0t.print/(6ocale.F>

  • 7/24/2019 IO Examples

    32/58

    &2

    &3

    'ystem.o0t.println(s4%L )) ![ I

  • 7/24/2019 IO Examples

    33/58

    &

    +

    2

    3

    5

    $

    79

    1;

    11

    1&

    1+

    12

    13

    15

    1$

    17

    19

    &;

    private int ho0rB min0teB secondL

    p04lic ?ime(int ho0rB int min0teB int second% N

    this.ho0r ho0rL

    this.min0te min0teL

    this.second secondL

    P

    )) et0rns a description in IHH:MM:''I

    p04lic 'tring to'tring(% N

    ret0rn 'tring./ormat(IU;&d:U;&d:U;&dIB ho0rB min0teB second%L

    P

    )) ?est main(%

    p04lic static void main('tringG args% N

    ?ime t ne= ?ime(1B &B +%L

    'ystem.o0t.println(t%L )) ;1:;&:;+

    P

    P

    1. File I*O in #D$ 1.%

    ?his section =as e@tracted /rom the "ava Online ?0torial and "D# $ >.G

    "D# 1.$ greatly enhances s0pports /or fle )O via ne= pac*agejava.nio.fleand its associated

    pac*ages.

    1.1 Inter'ace jaa.nio.7le.!at,

    >path stringco0ld 4e 0sed to locate a leB a directoryor a symbolic lin. > symbolic lin(or symlin% is a

    special fle that re/erences another fle. > path string is system dependentB e.g.B

    Ic:JmyprojectJjavaJHello.javaI in indo=s or I)myproject)java)Hello.javaI in ni@. indo=s 0ses

    4ac*!slash KJKas the directory separatorL =hile ni@es 0se /or=ard!slash K)K. indo=s 0ses semi!

    colon KLKas path separatorL =hile ni@es 0se colon K:K. ?he Ic:JI or IJI is called the root. indo=s

    s0pports m0ltiple rootsB each maps to a drive (e.g.B Ic:JIB Id:JI%. ni@ has single root (IJI%. > path co0ld4e absolute(4eginning /rom the root% or relative(=hich is relative to the c0rrent =or*ing directory%.

    'pecial notations I.I and I..I denote the c0rrent directory and the parent directoryB respectively.

    >java.nio.fle.athinstance specifes the location o/ a fleB or a directoryB or a sym4olic

    lin*. athreplacesjava.io.File(o/ the standard )O%B =hich is less versatile and 40ggy.

    1.; Heler class jaa.nio.7le.!at,s

    ?o create a athB 0se the staticmethod get(%o/ the helper classjava.nio.fle.aths. ?he helper

    class athscontains e@cl0sively staticmethods /or creating atho4jects. aths.get(%ret0rns

    aatho4ject 4y converting a given path string or .

    p04lic static ath et('tring rstB 'tring... more%

    )) ?his method accepts varia4le n0m4er o/ arg0ments (varargs%.

    )) t converts a path stringB or a se0ence o/ strings that =hen joined /orm a path stringB to a ath o4ject.

    )) ?he location o/ the ath may or may not e@ist.

    p04lic static ath et( uri%

    )) Converts the given to a ath o4ject.

    For e@ampleB

    ath p1 aths.get(Iin.t@tI%L )) > fle in c0rrent directoryB relative

    ath p& aths.get(Ic:JJmyproejctJJjavaJJHello.javaI%L )) FileB a4sol0teB need escape se0ence /or KJK

    ath p+ aths.get(I)0se)localI%L )) > directory

    >s the directory!separator is system dependentB /or =riting porta4le and more Qe@i4le programB it is

    recommended to 0se an e@isting athinstance as an anchor to resolve the flenameB e.g.B

    ath dir ...

    ath fle dir.resolve(IflenameI%L )) "oins the flename to the dirname =ith a directory!separator

  • 7/24/2019 IO Examples

    34/58

    > ath can 4e 4ro*en do=n as rootB level!;B level!1B .... ?he method get

  • 7/24/2019 IO Examples

    35/58

    ath path aths.get(Itest.jpgI%L

    'ystem.o0t.println(IFiles.'iAe(%: I R Files.siAe(path%%L

    )) re!"D# $: se java.io.File method aFile.length(%

    File fle ne= File(Itest.jpgI%L

    'ystem.o0t.println(IFile.length(%:I R fle.length(%%L

    Deletin a File*Directory

    o0 can 0se staticmethods delete(ath%to delete a fle or directory. Directory can 4e deleted only i/ it

    is empty. > 4ooleanmethod delete/E@ists(%is also availa4le.

    p04lic static void delete(athpath% thro=s OE@ception

    p04lic static 4oolean deleteI'E+ists(athpath% thro=s OE@ception

    Coyin*oin a File*Directory

    o0 can 0se staticmethods copy(athB athB CopyOption%or move(athB athB CopyOption%to

    copy or move a fle or directory. ?he methods ret0rn the target ath.

    ?he methods accepts an optionalthird arg0ment o/ CopyOption. For

    e@amples: CopyOption.E6>CEWEX'???,?E'copies the fle attri40tes s0ch as the

    datesL CopyOption.

  • 7/24/2019 IO Examples

    36/58

    p04lic static void main('tringG args% N

    'tring fle'tr IsmallWfle.t@tIL

    ath path aths.get(fle'tr%L

    )) 'trings =ith 0nicode characters

    6istT'tring[ lines ne= >rray6istT'tring[(%L

    lines.add(IHiBI%L lines.add(IHelloBVI%L

    )) rite to te@t fle in ?F!7

    try N

    Files.=rite(pathB linesB Charset./ort(i%L

    'ystem.o0t.print/(IUdGKUcK(U;2X% IB (iR1%B charO0tB (int%charO0t%L

    P

    'ystem.o0t.println(%L

    P

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    P

    P

    27 59 &C E5 7& >7 E3 >3 ,D &1 ;D ;>

    H i B C 6F

    27 53 5C 5C 5F &C E3 9; 7+ E9 >3 ,1 E2 ,> 75 E5 ,& >1 E5 9C 79 +F ;D ;>

    H e l l o B V C 6F

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%

    1GKHK(;;27% &GKeK(;;53% +GKlK(;;5C% 2GKlK(;;5C% 3GKoK(;;5F% 5GKBK(;;&C%

    $GKK(32;+% 7GKK(99$1% 9GKK(2E75% 1;GKK(5C>1% 11GKK(5$;9% 1&GKVK(;;+F%

    B2ered C,aracter"5ased I*O 'or Te+t Files

    For eadingB 0se Files.ne=,08eredeader(athB Charset%method to open a te@t fleB =hich ret0rns

    a ,08eredeader. se ,08eredeader.read6ine(% to read a lineB read(%to read a charB

    orread(charG c40/B int o8B int len%to read into a char!array.

    For ritingB 0se the Files.ne=,08eredriter(athB CharsetB OpenOption...%method to open a

    o0tp0t te@t fleB =hich ret0rns a ,08eredriter. se ,08eredriter.=rite(int c%to =rite a

    characterB =rite(charG c40/B int o8B int len%or =rite('tring sB int o8B int len%to =rite

    characters.p04lic static ,08eredeader ne3B2ered-eader(ath pathB Charset cs% thro=s OE@ception

  • 7/24/2019 IO Examples

    37/58

    p04lic static ,08eredriter ne3B2eredriter(ath pathB Charset csB OpenOption... options%

    thro=s OE@ception

    Byte"Based Strea/ I*O

    se Files.ne=np0t'tream(athB OpenOption...%to allocate an np0t'tream/or reading ra=

    4ytesL and Files.ne=O0tp0t'tream(athB OpenOption...%to allocate an O0tp0t'tream/or=riting. ?he np0t'treamand O0tp0t'treamret0rned are not 408ered.

    E+a/le 'imilar to the previo0s program =hich read)=rite the entire fleB this program read)=rite via

    ,08ered )O.

    import java.io.SL

    import java.nio.fle.SL

    import java.nio.charset.SL

    import java.0til.SL

    p04lic class B2eredFileIO#D$% N

    p04lic static void main('tringG args% N

    'tring fle'tr I408eredWfle.t@tIL

    ath path aths.get(fle'tr%L

    )) 'trings =ith 0nicode characters

    6istT'tring[ lines ne= >rray6istT'tring[(%L

    lines.add(IHiBI%L

    lines.add(IHelloBVI%L

    Charset charset Charset./or

  • 7/24/2019 IO Examples

    38/58

    P

    27 59 &C E5 7& >7 E3 >3 ,D &1

    H i B

    27 53 5C 5C 5F &C E3 9; 7+ E9 >3 ,1 E2 ,> 75 E5 ,& >1 E5 9C 79 +F

    H e l l o B V

    1GKHK(;;27% &GKiK(;;59% +GKBK(;;&C% 2GKK(5;>7% 3GKK(39$D% 5GKK(;;&1%$GKHK(;;27% 7GKeK(;;53% 9GKlK(;;5C% 1;GKlK(;;5C% 11GKoK(;;5F% 1&GKBK(;;&C%

    1+GKK(32;+% 12GKK(99$1% 13GKK(2E75% 15GKK(5C>1% 1$GKK(5$;9% 17GKVK(;;+F%

    Creatin a Ne3 File*Directory*Sy/lin0

    ,eside 0sing the Files.=rite(%method =ith OpenOptiono/ CE>?Eor CE>?EWttri40teTV[... attrs%

    ?he File>ttri40teincl0des: ?ODOG

    DO':

    ni@es: lso create the parent directory

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    Creatin a Te/orary File*Directory

    p04lic static ath createTe/File(ath dirB 'tringprexB 'tring su,xB

    File>ttri40teTV[... attrs% thro=s OE@ception

    )) Creates a ne= empty fle in the specifed dirB

    )) 0sing the givenprexand su,xto generate its name.

    p04lic static ath createTe/File('tringprexB 'tring su,xB

    File>ttri40teTV[... attrs% thro=s OE@ception

    )) Creates an empty fle in the de/a0lt temporary!fle directoryB

    )) 0sing the given pref@ and s0@ to generate its name.

    p04lic static ath create?empDirectory(

    ath dirB 'tring pref@B File>ttri40teTV[... attrs% thro=s OE@ception

  • 7/24/2019 IO Examples

    39/58

    p04lic static ath create?empDirectory(

    'tring pref@B File>ttri40teTV[... attrs% thro=s OE@ception

    E@ample: ?ODOG

    1.> File Attri52tes

    o0 can 0se one o/ the Files.read>ttri40tes(% methods to read all the 4asic attri40te o/ a path.

    p04lic static MapT'tringBO4ject[ readAttri52tes(

    athpathB 'tring attributesB 6in*Option... options% thro=s OE@ception

    )) ead eads a set o/ fle attri40tes.

    p04lic static O4ject etAttri52te(

    athpathB 'tring attributeB 6in*Option... options% thro=s OE@ception

    )) Yet a given attri40te

    p04lic static ath setAttri52te(

    athpathB 'tring attributeB O4ject valueB 6in*Option... options% thro=s OE@ception

    )) 'et a given attri40te

    1.@ FileC,annel

    p04lic static 'ee*a4le,yteChannel ne3ByteC,annel(

    athpathB OpenOption... options% thro=s OE@ception

    )) Opens or creates a fleB ret0rning a see*a4le 4yte channel to access the fle.

    p04lic static 'ee*a4le,yteChannel ne3ByteC,annel(

    athpathB 'etTV e@tends OpenOption[ optionsB File>ttri40teTV[... attrs%

    thro=s OE@ception

    )) Opens or creates a fleB ret0rning a see*a4le 4yte channel to access the fle.

    1. -ando/ Access File

    ?he nter/ace 'ee*a4le,yteChannels0pports random access.

    p04ic long osition(%

    )) et0rns this channelKs position.

    p04lic 'ee*a4le,yteChannel osition(long ne"Position%

    )) 'ets this channelKs position.

    p04lic int read(,yte,08er dest%

    )) eads a se0ence o/ 4ytes /rom this channel into the given ,yte,08er.

    p04lic int 3rite(,yte,08er source%

    )) rites a se0ence o/ 4ytes to this channel /rom the given ,yte,08er.

    p04lic long siMe(%

    )) et0rns the c0rrent siAe o/ entity to =hich this channel is connected.

    p04lic 'ee*a4le,yteChannel tr2ncate(long si'e%

    )) ?r0ncates the entityB to =hich this channel is connectedB to the given siAe.

    1.% Directory Oerations

    List all root directories

    )) rint the root directories /or the de/a0lt fle system

    tera4leTath[ rootDirs File'ystems.getDe/a0lt(%.getootDirectories(%L

    /or (ath rootDir : rootDirs% N

    'ystem.o0t.println(rootDir%L

    P

    Listin a directory

    o0 can list the contents o/ a directory 4y 0sing the Files.ne=Directory'tream(ath% method. ?he

    ret0rned Directory'treamo4ject implements tera4le. o0 can iterate thr0 the entries =ith /or!each

    loop.

    p04lic static Directory'treamTath[ ne3DirectoryStrea/(ath dir% thro=s OE@ception

    E+a/le 6ist the contents o/ a directory)) 6ist the contents o/ a directory

  • 7/24/2019 IO Examples

    40/58

    ath dir aths.get(I.I%L

    try (DirectoryStrea/Q!at,R dirStrea/ Files.ne3DirectoryStrea/(dir)% N

    /or (ath entry : dir'tream% N

    'ystem.o0t.println(entry.getFile globis a s04set o/ reg0lar e@pression.

    KSKmatches Aero or more character (;R%.

    KVKmatches any one character.

    KSSK4ehaves li*e KSKB 40t can cross directory 4o0ndaryB /or matching on /0ll path.

    N...B....B...Pencloses a set o/ s04!patterns separated 4y KBK. ...Gencloses a set o/ single character or a range o/ character =ith K!KB e.g.B aeio0GB a!AGB ;!9G.

    >ny other character matches itsel/. ?o match KSKB KVKor special charactersB pref@ =ith KJK.

    For e@ample: IhS.NjavaBclassBt@tPI matches entry starts =ith IhI and ends =ith I.javaIB I.classIB or

    I.t@tI.

    o0 can also =rite yo0r o=n codes to flter the entries.

    p04lic static Directory'treamTath[ ne3DirectoryStrea/(

    ath dirB Directory'tream.FilterTV s0per ath[ lter% thro=s OE@ception

    ?he inter/ace Directory'tream.FilterT?[declares one a4stract4ooleanmethod accept(%B =hich

    =ill 4e call!4ac* /or each entry. ?hose entries that res0lted in /alse accept(%=ill 4e discarded.

    p04lic 4oolean accet(? entry% thro=s OE@ception

    E+a/le ?he /ollo=ing program 0ses an anonymo0s instance o/ an

    anonymo0s Directory'tream.Filter s04!class to flter the Directory'tream. ?he call!4ac*

    method accept(%ret0rns tr0e/or reg0lar flesB and discards the rest. ?a*e note that this fltering

    criterion cannot 4e implemented in a glo4!pattern.

    )) 6ist the contents o/ a directory =ith a c0stom flter

    ath dir aths.get(Id:JJtempI%L

    try (Directory'treamTath[ dir'tream Files.ne=Directory'tream(dirB

    ne3 DirectoryStrea/.FilterQ!at,R() 4 ** anony/o2s inner class

    25lic 5oolean accet(!at, entry) t,ro3s IOE+cetion 4

    ret2rn (Files.is-e2larFile(entry))9 ** re2lar 7le only

    :

    :%% N

    /or (ath entry : dir'tream% N

    'ystem.o0t.println(entry.getFile

  • 7/24/2019 IO Examples

    41/58

    'ystem.o0t.println(entry.to'tring(%%L )) F0ll!path name

    P

    P catch (OE@ception e@% N

    [email protected]'tac*?race(%L

    P

    1. al0in t,e File Tree " Files.3al0FileTree()

    o0 can 0se staticmethod Files.=al*File?ree(%ro rec0rsively =al* thr0 all the fles /rom a starting

    directory.

    First o/ allB yo0 need to create an o4ject that implements inter/ace FileZisitorTV s0per ath[B =hich

    declares these a4stractmethods:

    p04lic FileZisites0lt re&isitDirectory(? dirB ,asicFile>ttri40tes attrs% thro=s OE@ception

    )) nvo*ed /or a directory 4e/ore entries in the directory are visited.

    )) / this method ret0rns CO

  • 7/24/2019 IO Examples

    42/58

    'ystem.o0t.print/(I'ym4olic lin*: Us IB fle%L

    P else i/ (attr.iseg0larFile(%% N

    'ystem.o0t.print/(Ieg0lar fle: Us IB fle%L

    P else N

    'ystem.o0t.print/(IOther: Us IB fle%L

    P

    'ystem.o0t.println(I(I R attr.siAe(% R I4ytes%I%L ret0rn CO

  • 7/24/2019 IO Examples

    43/58

    O-E -EFE-ENCES = -ESO-CES1. "ava Online ?0torial on I,asic )OI

    \ http:))do=nload.oracle.com)javase)t0torial)essential)io)[email protected] in partic0lar IFile )O

    (Feat0ring

  • 7/24/2019 IO Examples

    44/58

    Read and write text files without buffering

    classic example for reading and writing to a text file

    ?

    1

    &

    +

    2

    3

    5

    $

    7

    9

    1;

    11

    1&

    1+

    12

    13

    15

    1$

    17

    19

    &;

    &1

    FileReader reader = null;

    FileWriter writer = null;

    try{

    reader = newFileReader("in.txt");

    writer = newFileWriter("out.txt");

    inta = 0;

    while((a = reader.read()) != -1) {

    writer.write(a);

    }

    } catch(FileotFoundxcetion e) {

    e.rint#tac$%race();

    } catch(&'xcetion e) {

    e.rint#tac$%race();

    } inally{

    try{

    reader.cloe();

    writer.cloe();

    } catch(&'xcetion e) {

    e.rint#tac$%race();

    }

    }

    Read and write text files with buffering

    Reading and writing using buffered reader and writer. Note the use of the apache IOUtils class to close the stream.

    ?

    http://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsp
  • 7/24/2019 IO Examples

    45/58

    1

    &

    +

    2

    3

    5

    $

    7

    9

    1;

    11

    1&

    1+

    12

    13

    15

    1$

    17

    19

    &;

    &1

    &&

    *ueredReader +ueredReader = null;

    *ueredWriter +ueredWriter = null;

    try{

    +ueredReader = new*ueredReader(new FileReader("in.txt"));

    +ueredWriter = new*ueredWriter(new FileWriter("out.txt"));

    #trin, = "";

    while(( = +ueredReader.readine()) != null) {

    +ueredWriter.write();

    write a new line

    +ueredWriter.newine();

    luh

    +ueredWriter.luh();

    }

    } catch(FileotFoundxcetion e) {

    e.rint#tac$%race();

    } catch(&'xcetion e) {

    e.rint#tac$%race();

    } inally{

    cloe without throwin, excetion

    &'/til.cloeuietly(+ueredReader);

    &'/til.cloeuietly(+ueredWriter);

    }

    Read Unicode file

    The following example demonstrates how to read a file encoded in unicode

    V

    ead and rite characters 0sing rintriter

    1 Reader reader/nicode =

    http://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsp
  • 7/24/2019 IO Examples

    46/58

    &

    +

    2

    3

    5

    $

    7

    new&nut#treaReader(new File&nut#trea("in/nicode.txt")2 3haret.orae("/%F-14")

    inte = 0;

    while((e = reader/nicode.read()) != -1) {

    cat to char. %he catin, reo5e the let ot +it.

    char = (char) e;

    #yte.out.rint();

    }

    Reading and Writing - Convenient methods

    Get the contents of an input stream as byte array

    V

    1

    &

    +

    2

    inut#trea = newFile&nut#trea(ile);

    +yte67 data = &'/til.to*yte8rray(inut#trea);

    or

    +yte67 data=File.read8ll*yte(teFile9ath);

    Yet the contents o/ inp0tstream as list o/ 'trings

    V

    1

    &

    +

    2

    it:#trin, line = &'/til.readine(inut#trea);

    or

    it:#trin, line=

    File.read8lline(teFile9ath2 #tandard3haret./%F =

    &'/til.to&nut#trea("#trin, to +e con5erted to inut trea");

    rite array o/ 4ytes to o0tp0t stream.

    http://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsphttp://www.studytrails.com/java-io/character-file-reading-writing.jsp
  • 7/24/2019 IO Examples

    47/58

    V

    1

    &

    +

    2

    'utut#trea outut#trea = newFile'utut#trea(ile);

    &'/til.write(data>2 outut#trea);

    write +yte array to a ile. data i a +yte array.

    File.write(teFile9ath2 data2#tandard'en'tion.899?);

    rite a collection o/ lines to o0tp0tstream

    V

    1 &'/til.writeine(line2 null2 outut#trea);

    read the contents o/ a fle into a string. ?here is a similar =rite method too.

    V

    1 File/til.readFile%o#trin,(ile2 trin,));

    ead fle into a list o/ strings

    V

    1 it:#trin, line = File/til.readine(ile));

    0se java.io.fle.Files to get a 408ered readerB =riter and inp0tstream

    V

    1

    &

    +

    2

    3

    5

    $

    7

    9

    *ueredReader reader =

    File.new*ueredReader(teFile9ath2#tandard3haret./%F

  • 7/24/2019 IO Examples

    48/58

    FileInputStream- This stream reads raw bytes from a file. The read methods in this class return a byte of data

    read from a file.

    ObjectInputStream- This class is used to read objects written using ObjectOutputStream. It deserializes the

    primitive data types and objects

    PipedInputStream- A unix 'pipe' like implementation can be accomplished using this class. It can connect to a

    pipedoutputsteam and read data off it.

    BufferedInputStream- This is probably the most used class. It buffers the data from any of the above

    inputstream. The methods in this class increase reading efficiency since they try to read the maximum number

    of bytes that can be read from the file system in one operation.

    ByteArrayInputStream-This class contains a buffer(array) or bytes that store the next few bytes that will be read

    from the stream.

    Writing Bytes - classes

    All classes that write bytes extendjava.io.OutputStream. The important classes are:

    FileOutputStream- The methods in this class write bytes of data to a file. Note that this writes raw bytes and

    not characters.

    ObjectOutputStream - writes primitive java types and objects to an ouputstream. The data could be written to a

    file or to a socket. Data written using this method can be read back using the ObjectInputStream

    PipedOutputStream- A piped output stream connects to a PipedInputStream to read bytes. Data may be

    written by one thread and read by another.

    BufferedOutputStream-It buffers data from an inputstream and writes the buffered data. It is an efficient

    method of writing data since the operating systems may write an array of bytes in a single operation and

    invoking write operation for each byte may be inefficient

    PrintStream-It wraps an InputStream and adds functionality to print various representations of data values. It

    never throws IOException and there is an option for automatic flushing

    ByteArrayOutputStream-This class writes bytes at an array of bytes.

    Example- Read and write without buffering

    Read bytes from a file and write to another file.

    V

    File! ead and rite 4ytes

    1

    &

    +

    File'utut#trea out = newFile'utut#trea("oututFile");

    &nut#trea inut = newFile&nut#trea("inutFile");

    inta = 0;

    while(a != -1) {

    http://www.studytrails.com/java-io/byte-reading-writing.jsphttp://www.studytrails.com/java-io/byte-reading-writing.jsp
  • 7/24/2019 IO Examples

    49/58

    2

    3

    5

    $

    7

    9

    a = inut.read();

    out.write(a);

    }

    inut.cloe();

    out.cloe();

    Example- Read and write with buffering

    use a Buffer to read and write bytes

    V

    File! ead and rite 4ytes

    1

    &

    +

    2

    3

    5

    $

    7

    9

    1;

    11

    1&

    1+

    12

    13

    15

    1$

    *uered'utut#trea +uered'ut = new*uered'utut#trea(new File'utut#trea("ou

    the content o in.txt ile are "onetwice$iend"

    Read the irt three char+yte once2 read the next i5e twice2 $i the next our

    *uered&nut#trea +uered&nut = new*uered&nut#trea(newFile&nut#trea("in.

    int+ = 0;

    +yte67 irt%hree = new+yte6@7;

    +uered&nut.read(irt%hree);

    con5ert the array o +yte to character uin, the deault encodin,.

    #yte.out.rintln(3haret.deault3haret().decode(*yte*uer.wra(irt%hree)));

    ar$ the current oition2 ince we would read thi a,ain. %he ar$ oition i

    +uered&nut.ar$(4);

    read the next i5e +yte

    +yte67 nextFi5e = new+yte6A7;

    +uered&nut.read(nextFi5e);

    http://www.studytrails.com/java-io/byte-reading-writing.jsphttp://www.studytrails.com/java-io/byte-reading-writing.jsp
  • 7/24/2019 IO Examples

    50/58

    17

    19

    &;

    &1

    &&

    &+

    &2

    &3

    &5

    &$

    &7

    &9

    +;

    +1

    +&

    ++

    +2

    +3

    +5

    +$

    +7

    +9

    2;

    21

    2&

    #yte.out.rintln(3haret.deault3haret().decode(*yte*uer.wra(nextFi5e)));

    ,o +ac$ to the ar$ed oition and read it a,ain

    +uered&nut.reet();

    +yte67 read%heFi5e8,ain = new+yte6A7;

    +uered&nut.read(read%heFi5e8,ain);

    #yte.out.rintln(3haret.deault3haret().decode(*yte*uer.wra(read%heFi5e8,ain

    $i the next our

    +uered&nut.$i(B);

    read the lat three

    +yte67 lat%hree = new+yte6@7;

    +uered&nut.read(lat%hree);

    #yte.out.rintln(3haret.deault3haret().decode(*yte*uer.wra(lat%hree)));

    write to the outut trea

    +uered'ut.write(irt%hree);

    +uered'ut.write(nextFi5e);

    +uered'ut.write(read%heFi5e8,ain);

    +uered'ut.write(lat%hree);

    +uered'ut.luh();

    +uered&nut.cloe();

    +uered'ut.cloe();

    Java IO - Read and Write Java Objects

    Introduction

  • 7/24/2019 IO Examples

    51/58

    ObjectInputStream can be used to de-serialize and read java objects that have been serialized and written using

    ObjectOutputStream. In the example below the 'Course' object is written to a persistent storage. The Course object

    contains a list of Student objects. The object writing preserves object references. We first create an object output stream

    that stores the bytes to a file using a FileOutputStream.

    V

    Create an o4ject o0tp0t stream.

    1

    &

    +

    2

    3

    5

    $

    7

    9

    1;

    11

    1&

    1+

    12

    13

    15

    1$

    17

    19

    &;

    &1

    &&

    &+

    '+Cect'utut#trea o+Cect'utut#trea = new'+Cect'utut#trea(

    newFile'utut#trea("Ca5a'+Cect.txt"));

    write a date

    o+Cect'utut#trea.write'+Cect(new ?ate());

    write a +oolean

    o+Cect'utut#trea.write*oolean(true);

    write a loat

    o+Cect'utut#trea.writeFloat(1.0);

    the other riiti5e tye and o+Cect can +e a5ed a well

    create two tudent o+Cect and add the in a lit. create a coure

    o+Cect and add the lit o tudent to a lit

    #tudent tudent1 = new#tudent();

    tudent1.et8,e(@0);

    tudent1.etae("#tudent1");

    #tudent tudent> = new#tudent();

    tudent>.et8,e(@1);

    tudent>.etae("#tudent>");

    3oure coure = new3oure();

    coure.etae("Da5a &'");

    it:#tudent tudent = new8rrayit:();

    tudent.add(tudent1);

    tudent.add(tudent>);

    http://www.studytrails.com/java-io/read-write-java-objects.jsphttp://www.studytrails.com/java-io/read-write-java-objects.jsp
  • 7/24/2019 IO Examples

    52/58

    &2

    &3

    &5

    &$

    &7

    &9

    +;

    +1

    +&

    ++

    +2

    +3

    +5

    +$

    +7

    +9

    2;

    21

    2&

    2+

    22

    23

    25

    2$

    27

    29

    3;

    31

    coure.et#tudent(tudent);

    write the coure o+Cect to the o+Cectoututtrea. %hi write the

    o+Cect a well all o+Cect that it reere to.

    it write only thoe o+Cect that ileent erialiEa+le

    o+Cect'utut#trea.write'+Cect(coure);

    o+Cect'utut#trea.luh();

    o+Cect'utut#trea.cloe();

    the o+Cect inut trea read the o+Cect +ac$ ro the ile and

    create Ca5a o+Cect out o the. &t recreate all

    reerence that were reent when the o+Cect were written

    '+Cect&nut#trea o+Cect&nut#trea = new'+Cect&nut#trea(

    newFile&nut#trea("Ca5a'+Cect.txt"));

    tart ,ettin, the o+Cect out in the order in which they were written

    ?ate date = (?ate) o+Cect&nut#trea.read'+Cect();

    #yte.out.rintln(date);

    #yte.out.rintln(o+Cect&nut#trea.read*oolean());

    #yte.out.rintln(o+Cect&nut#trea.readFloat());

    ,et the coure o+Cect

    3oure read3oure = (3oure) o+Cect&nut#trea.read'+Cect();

    #yte.out.rintln(read3oure.,etae());

    #tudent tudent1Read = read3oure.,et#tudent().,et(0);

    #yte.out.rintln(tudent1Read.,et8,e());

    #yte.out.rintln(tudent1Read.,etae());

    o+Cect&nut#trea.cloe();

  • 7/24/2019 IO Examples

    53/58

    3&

    3+

    32

    ?he Co0rse Class

    V

    Create an o4ject o0tp0t stream.

    1

    &

    +

    2

    3

    5

    $

    7

    9

    1;

    11

    1&

    1+

    12

    13

    15

    1$

    17

    19

    &;

    u+liccla#tudent ileent#erialiEa+le {

    ri5ate#trin, nae;

    ri5ateinta,e;

    u+lic#trin, ,etae() {

    returnnae;

    }

    u+lic5oidetae(#trin, nae) {

    thi.nae = nae;

    }

    u+licint,et8,e() {

    returna,e;

    }

    u+lic5oidet8,e(inta,e) {

    thi.a,e = a,e;

    }

    }

    ?he 't0dent Class

    V

    http://www.studytrails.com/java-io/read-write-java-objects.jsphttp://www.studytrails.com/java-io/read-write-java-objects.jsphttp://www.studytrails.com/java-io/read-write-java-objects.jsphttp://www.studytrails.com/java-io/read-write-java-objects.jsp
  • 7/24/2019 IO Examples

    54/58

    Create an o4ject o0tp0t stream.

    1

    &

    +

    2

    3

    5

    $

    7

    9

    1;

    11

    1&

    1+

    12

    13

    15

    1$

    17

    19

    &;

    u+liccla3oure ileent#erialiEa+le {

    #trin, nae;

    it:#tudent tudent;

    u+lic5oidetae(#trin, nae) {

    thi.nae = nae;

    }

    u+lic5oidet#tudent(it:#tudent tudent) {

    thi.tudent = tudent;

    }

    u+lic#trin, ,etae() {

    returnnae;

    }

    u+licit:#tudent ,et#tudent() {

    returntudent;

    }

    }

    Read and Write a file in Java using Buffered Streams - Java IO(Buffered Streams)

    NAKESH CHAHAN11>@ CO-E"#A&A6#A&A"IONO COENTS

    In our previous discussions we came across Byte Streams and !"aracter Streams in Java# In t"is particular $log we

    will dive into Buffered Streams# We will come to %now "ow to read from and write to a file in &ava using Bufferd

    Streams and w"y t"is is a good practice to use $uffered streams over $yte and c"aracter streams#

    In case of $yte and c"aracter streams every $yte or piece of data t"at s $eing read or write re'uires an direct support

    from underlying OS $ecause of not "aving an intermediate $uffer included# "is ma%es a etensive use of memory and

    https://plus.google.com/113669883250831796053http://www.beingjavaguys.com/search/label/core-javahttp://www.beingjavaguys.com/search/label/java-iohttp://www.beingjavaguys.com/search/label/java-iohttp://www.beingjavaguys.com/2013/11/buffered-streams-in-java.html#comment-formhttps://plus.google.com/113669883250831796053http://www.beingjavaguys.com/search/label/core-javahttp://www.beingjavaguys.com/search/label/java-iohttp://www.beingjavaguys.com/2013/11/buffered-streams-in-java.html#comment-form
  • 7/24/2019 IO Examples

    55/58

    resources# On t"e ot"er "and Buffered streams wor%s as a wrapper to "old un$uffered streams and ma%e it possi$le to

    store $unc" of data or $ytes in $uffers (memory)# "e underlying OS resource are needed only w"en t"e $uffer is full or

    empty and not on every instance of read or write#

    "e native input *+I is called only w"en t"e $uffer is empty# Similarly, $uffered output streams write data to a $uffer, and

    t"e native output *+I is called only w"en t"e $uffer is full# n$uffered streams can $e converted to $uffered streams $ywrapping t"em in a constructor of Bufferd Stream class as s"own $elow#

    !onvert $yte Stream to Buffered $yte Stream

    Read and Write file using BufferedInputStream and

    BufferedOutputStream classes# BufferedInputStream and BufferedOutputStream clases are used to ma%e $uffered

    $yte streams $y wrapping InputStreamReader and OutputStreamWriter classes#

    view plain print ?

    1. ac0aecom.4eingjavag0ys.coreL

    &.

    +. i/ort java.io.,08erednp0t'treamL

    2. i/ort java.io.,08eredO0tp0t'treamL

    3. i/ort java.io.Filenp0t'treamL

    5. i/ort java.io.File

  • 7/24/2019 IO Examples

    56/58

    &1. 4os ne3,08eredO0tp0t'tream(ne3FileO0tp0t'tream(

    &&. Ifles)destination.t@tI%%L

    &+. intdataL

    &2. 3,ile((data 4is.read(%% !1% N

    &3. 'ystem.o0t.println(data%L

    &5. 4os.=rite(data%L

    &$. P

    &7. P catc,(File

  • 7/24/2019 IO Examples

    57/58

    $. i/ort java.io.FileriterL

    7. i/ort java.io.OE@ceptionL

    9. )SS

    1;. S \a0thor

  • 7/24/2019 IO Examples

    58/58

    /ere we are done wit" 0Read and Write a file in Java using 0Byte Buffered Streams0 and 0!"aracter Buffered Streams0# In

    our upcoming $logs we will see more a$outJava +rogramming and ot"er opensource tec"nologies#

    http://www.beingjavaguys.com/p/core-java.htmlhttp://www.beingjavaguys.com/p/core-java.htmlhttp://www.beingjavaguys.com/p/core-java.html