You are on page 1of 194
| i 322 | Chapter 23 | aa ————___ Enter address: nyderabag Enter id: 11 Enter nane: Kumar Enter address: Nen Delhi | enter id: 12 Enter nane: Ganesh Enter address: Mumbai Enter sds 13 Enter name: Nehru Enter address: chennai Enter id: 1a Enter. nane: chandana Enter address? Kolkata enter, id to seareht 13 Name: Nehru Address: Chennai Brett cateretand tne ogc weed in nc Hee || « search ors | = ob Employee cass objects ym an ArrayList Figure 23.5 Retrieving objects using Bet()fror CHAPTER STREAMS AND FILES send or receive data through different sources, such as to receive data from keyboard, we need a stream and to send data to a file, we need another stream. Without streams, it is not Possible to move data in Java. Stream Asean carries data just as a water pipe carries water from one place to another {figure 24.1). Streams can be categorized as ‘input streams’ and ‘output streams’, Input streams are Streams which receive or read data while output streams are the streams which send or write ala All streams are represented by classes in java.io (input-output) package. Sas facilitate transporting data from one place to another. Different streams are needed to Figure 24.1 A stream to move data mets see how a stream works. We know an input steam reads dats, So, to ead data fom ‘Yped on 1 We can attach the keyboard to an input stream, so that the stream can reat '0n the keyboard. ee as itanntstrean dis one {nthe aby stream object. The keyboard is ove statcment, we are attaching the keyboard to Datarapat Stream obj a ee a ee oot ees om oa Here, system is a class and in is a field in system class. In fact, the System class has glowing 3 felas oo tis keyboard by default a outeh, Out: represents Printstrean object: This object by default represents the st SUtput, device, that is monitor. — 324 | Chapter 24 “s Q systen.err: represents Printstream object. This object by d output device, that is monitor. fault represents the stander! So, We can also use Systen.err to print something on the monitor, just Ii Queition Whats the difference between System.out and System err ? Both are used to display messages on the monitor. System.out is used to display nome messages as: ‘System.out printin( Hello’); ‘System errs used to display any error messages in the program as. ‘System err printin(‘This is an error’); Please observe that the Keyboard is represented by System.in which internally cea represented by eect cncan® he Keyboard is an InputStroan, Similarly, the saat § represented by PrintStrean, In this way, streams represent input/output devices in Java Bret We change the keyboard or monitor, we can still use the same streams to handle those devices ft this way, streams are useful to handle the input/output devices irrespective of their make. di Qecstion a What is the advantage of stream concept? ‘Streams are mainly useful to move data from one place to another place. This to receive data from an input device and send data to an output device concept can be ud : a the it Classification of streams is ‘byte streams’ and ‘ext streams’. Byte streams represent ac! {ie form of individual bytes. Text streams represent data as characters of each 2 bytes I o Sane, pads with the word ‘Stream’, then it comes under byte streams. Inp..cst ream reads byl OutputStream writes bytes. For example: _ ae Filernputstrean =: Fileoutputstrean Bufferedinputstream Bufferedoutputstream ———_ oa dt eadglass name ends with the word ‘Reader’ or Writer then it le taken ax a wext stream RO reads text and Writer writes text. For example, __— ag Ee ————— Filewriter Sufferedaeader Sufferedwriter (text), images, audio, and video files. Fo rye 80 for a byte stream. The important clas “ Streams and Files | 325 InputStream |_[ByteArrayinputStream BuiferedinputSteam —|FieinputStream ci |[Pipeainputstream teestedstecn | | fFiterinputSteam [LineNumberinputStream DatalnputSveam _fobjectinputSiream Figure 24.2(a) byte stream classes for reading data [CutputStream| | [evearayOupuisvean |_ticoutputSteam | BufferedOutputStream —FilterOutputStream pee, oe es {objectOutputStream Deel, Figure 24.2(b) byte stream classes for writing data Character or text streams can always store and retrieve data in the form of characters (or text) only. Iemeans text streams are more suitable for handling text file like the ones we ereate in Notepad They are not suitable to handle the images, audio, or video files. The important classes of character Streams are shown in Figure 24.3{a) and 24.3(b). ieNumberReader | BufferedReader as ‘CharArrayReader FiterReader inptSvear Reade {riekeoir | —|PipedReader — ‘StingReader ire 24.3(a) text stream classes for reading data Figu ee l0lUlUlUllllll””~”~C nar AtayWrter FiterWiter PrpedWrter Preirter Stinger Figure 24.3(b) tox: stream classes for writing data Creating a file Using FileOutputStream We know th, Stores the data in the form of individual bytes. tepe ace spresents storage af date on ae (ad my THe following steps nee? be followed to create a text fle that © el oh, we ros read data from the keyboard. For this Purpose, we should attach the om am class. The code ier, 88 Patarnputst ream class for reading Mtertitreaeis < new Datarnputsen, ‘eam(sy: ‘Sam. Here, we take the help NE the file myfile.txt to nag tt into P11 couples ee 'S shown here: ee $ the assoeissctiON8 on it, else the data df ence then gasOCited sinc sel example, Mes mene Ae Ina wae “rite data into the file. Togram 1 ams and Files | 927 Datainputstream | eee . ‘System in Figure 24.4 Cresing ema fie.” ri Pars Program 1: Write a program which shows how to rei ‘ j et fhich shows how to read data from the ke . yiereating a text file using Fi leoutputstream gay aieext file ust PA Class createrie public static void main(string a Be eis See tM /yattach keyboard, to batarnpurstreas aah eae is = Rew DAtalNputstTeanmnneen aE [/actach myfile 9 Ejleoutpusstesie, * (iSoutputscream fout = new TF coacputserean( mph ie tt Fe Co at the one! FE system.out.printinC"enter cext char chi /ivead characters, from. gi5,Inhagg then [prea cers as. long 88,66 fet ‘cnaracter [pcenest, Menaryaiseread@) !* 0) fout.write(ch) i - ‘close the file ' Usreeiose0: Output; scam gavac _createrile- NS Fava createFile 4): Eitoe tex co. at, tne end)! Ithis 4s my file Tine Ofe This is my file Tine two i yay File iine one js dsiay fire vine O° Tae ene kesbont en he m oe user PS © OE ee rm, we read 4302 Keyboard tert fe in UNIX In this progra accepts data from the Here, we stored two lines of type command in DOS or a! = For exa" ———— [—[etararaynter —] |—fFiterwiter {oupistieamwraer }+-—[ Fewer Fy] Figure 24.3(6) texe stream classes for writing data Creating a file using FileOutputStream Fileo ie stream and stores the data in the form of individual byt sents storage of data on a second smn owing steps are to be followed to create a text file pose, we should attach the oputstrean class fr rai » fout represents the Fite serean. It mrad data from Datarnputstrean and Write it into Fileoutputs! mm dis object and write it into tour Object, as shown here: | ch =(charddis rea is read: T7reag abrsitecch): /piriea oe ‘into Figeraete" into ch OutputStream object, — Streams and Files | 327 DatainputStream FileOutputStream ee Systemin Tnyfle bt Figure 24.4 Creating a text fle Program 1: Write a program which shows how to read data from the keyboard and write it to nyfile. txt file [/creating a text File using Fi leoutputstream ‘import. java.io. *; glass creatervie public static void main(string args 1) frrows ToException //attach keyboard to Datarnputstrean : Oatarnputstream dis = new DatarnputStrean(system. in); attach, jle to Fileouty a: $ ah (4iisbacputSerean Pout = new Fiteoutpurstream("ayFite.tx system. out.print1n ("Enter text (@ at the end): "); char ch; //vead characters from dis into ch. then write then into fout. ‘Jyrepeat ‘this as Tong as the read character is not @ whiteC(ch =(char)dis.read()) I= '@") Fout.write ch); ‘ z {/close the file ou fout.closeQ; 4 i f 3 y Output: ee UL Ci\> javac Createrilevjavaii A Ci\> Java cresteriles 2 Feds Enter text (@ at the end): Ns is my file line one Ms is ny File Tine tho £:\> type Be PST on ‘is my file Tine two In this program, we read data from the keyboard and write it to myfile. txt file. This program Accepts data from the keyboard till the user types @ when he does not want to continue. fete, we stored two lines of text into myfite. txt. To view the contents of myfile.txt, ¥Pe command in DOS or cat command in UNIX. For example, we can use = Writer | ra Heer) ne OutputStreamivriter PipedWitar ee | [Printer ‘stinger ] Figure 24.3(b) text stream classes for writing data some characters (or text) First ofall, we should read data from the ke Keyboard to some input stream class, The data from the keyboard is as: attach the Saboart. For this purpose, we should ah ode for using Datatnput stream class cam object, that 9 Now, attach a fle where the data is to b of Fileoutputstream which can sen FileOutputstream can be done as: the help Fs fome ouput steam, Here we tke id data to the file. Attaching the file myf: Fileoutputstream Fout = new Fila ‘Outputstream("myFile. txt In the above statement, O The next step is to means read data fro Fout represents the Pi 1eoutputs: read data from Datainputstrea, mm dis object and write it into to, tream object. a im and write it into Fi leoutputst! ut abject, as shown here: gh =(char)dis.read(); Bh gichandis.reaac {read one = = SEs atinel nto Fine ate NEO. ch Streams and Files | 327 DatalnputSteam utputStream a ees Systemin myilobt Figure 24.4 Creating a text file Program 1: Write a program which shows how to read data from the keyboard and write it to myfile.txt file Z/creating a text file using Fileoutputstrean import java. io.*; Glass createriie public static void main(string args ]) - fhrons ToExcention : //attach keyboard to Data=nputstream datainputstrean dis = new Datalnputstream(systen. in); J/attach myfile to Fileoutputstream {4icbacputgerean Pout = new Fileoutputstrean(*ayFi te. ex systen.out.printIn("enter text (@ at the end): char ch i te //read characters from dis into ch. Then write them into fout. 7/repeat this as Jong as the read character is not @ while((ch =(char)dis.readQ)) != "@") ¥ fout.write(ch); i J/close the file eae i oe four-closeO: i Output: COCO t\> javac Createrileijava : ‘ Gi java crestertle | Enter text (@ at the end): This is my file Tine one Ths is my File Tine tho Gi\> type myfile, txt ae ea i's is my file line one a 2 is is my File line two : 2 this program, we read data from the keyboard and write it t9 myfite, txt file. This program Accepts data from the keyboard till the user types @ when he does not want to continue, fete, we stored two lines of text into myfi le. txt. To view the contents of myfite, txt, we can use Ye command in DOS or cat command in UNIX. For example, 328 | Chapter 24 c ——— e myfile. txt WHF BSptay the contents of nyfilete, a 1’ Program 1 is executed again, the old data of ny€ile.txt will be lost and any recent data eo stored into the file. Ci\> java Createrile ae Enter'Gexe Cae ‘the end): Uns is my third Tine > type myfile. ext This is my third Tine == peaegaat the fle myfile-txt has now stored only the third line which has been enteral oe Perea es oes Output. The previous two lines have been deleted from the file and the fle — Dow date nt icstt lle. If we do not want to Jose the previous data of the file, and just a? Ph tee eat the Gnd Of already existing data, then we should open the ‘ile by wiiing true am with the filename as: Fileoutputstreaw/fout =\new FiTeoutputstreanCmyfile.txt", true); When the above statement is used—even thou, igh the program is run several times—all previ data will be preserved ai ind new data will be added to the old data, Improving Efficiency using BufferedOutputStream Normally, whenever we write data into a file using ?1eout putstre: fout.write(ch); Here, we call write) method on fout the file. Here, the Fi f : ¢ keyboard 6 6 Tam into ‘a file. Let us assume we med data from the keyboard into memory ws! PatalnputStream and it takes 1 second tim: e to tead 1 character into memory. Let us a putStream by spending another 1 second ad and enaaier, a total time of 2 seconds are used. Thus, t0 Te Seconds time. This is wasting if Buffered classes are use this character is written into the file by FileOce, for reading and writing a single ch. write 100 characters, it takes 200 On the other hand, which is first filled alot of time ie they provide aber (temporary Hock o mma n all the characters from the buffer can classe should be used always in connection to other sean ae an be used along with FileOutputStrearn to write fer Pane MieOutputstream wil write the entire UE his is like writing a single character into the ers, i 1 second time. So, to read and write 100 charac classes in the Figure 24)5 i Streams and Files | 329 ‘Buteredoutputstream eae Fuleourpurstrean| [a] Figure 24.5. Using BufferedOutputStream to improve performance In Program 1, we can attach FileOutputStream to BufieredOutputStream as: Sufferedoutputstream bout = new Bufferedoutputstrean(Fout) 1024) Here, the butter size is declared a8 1024 bytes. If the buffer size is not specified, then a default hufler size of 512 bytes is used. PRE 1 tsiew Question What is the default buffer size used by any buffered class? 512 bytes. Program 2: Write a program to improve the efficiency of writing data into a file using Butferedoutp: Here, we are rewnrting Program 1 using BulferedOubputSiream where the file is opened for appending ata [Creating a text File using Bufferedoutputstream import java.io.*; Flass creatersie public static void main(string args{ 1) Phrons IOException attach keyboard to oatatnputstreas Gs eestaueStteam dis ~ ne patainputstrean(system,in); i nem Caestrean in append node | {attach myfile to Fi leoneiies leoutputstream(’nyfile.txt”, true); Fleouxpucstrean four ean ro purreredoutputstream oe | oy). cei eacjoutpuestrean bout = new sufferedoutputstream (four, 3 System. out.printIn("enter ‘text (@ at the end): DF char chy Per ae ir from dis into ch. Then write then into bout, Jyread characters, orotas the read character 15 rot @ while((ch ‘=(char)dis.read(. d bour.wri tech): {iclose the file foutscloseO: ————————— Sie Javac createrive. java ENS fava‘crestert ie Saige text (8 at the end): Tis is wy File Tine four IMs fs Tast Tine ’ yt iw | This {3 wy file Vine four TMS 15 Tas t Tine Reading Data fro M a File usin useful to re mM a text file using fi ie file in the fo ean. Let us 5 fin us to read data fr om the file Then, to rea e read() ‘or. For dis ean object I "Stream and utpUut stream, ig FileInputStream Sequence of bytes, It is possible it is done d “ata from the file, we should read dita it reaches t : he end of the file, When metho od returns ) example ‘cream, so that the i th we can use system. laying the data, Write it to system. out This will displey — Streams Program 3: Write a program to read data from myfile txt using Pile on the monitor. Outs roem and diag Beaitett ie using.rize inputstream class ReadFile * public static void main(string ar; throws IOException Strid. ecastede Jfattach the file to FileInputstream *ietapurserean Fins= new Fi leinputsereanCnyf ile. txt) System.out.printin("File contents: //read characters from Ep canna and write them Ukomonitor, Repeat this till the end of file. ‘int ch; while((ch= fin.read()) iy System .out.p! int ((char).ch)} Jfelose the file fin.closeQ; gavac)ReadFile. java java ReadFile ‘ dontents: This is my third line This is my file line four This is last Tine ta corneas n. First, the above p in the above program ab ye should # There are some improvements suggestib ne with myfile.txt ay To make this Pra ane tS kee from the keyboard. For this purpose, create © ata = “br pufferedneader eee sates He ea im) is attached nea that Ho actualy roel Boe lere, the ard (SYS! n) sue a Pent egecer Go it we read date Om ee ear : keyboard. Using readiine() method 0! from the Keyboard as: : i ~ ading dat String fname Tiana sue b 9 pilerapatst This filename should be attached °F Filernputstream fin What happens if the file being OFT By handling this exception, itis POST i reamcfnane) BEVEL new Fivexneutes } dis net ple to Know

You might also like