You are on page 1of 19
Input and Output Introduction Input and Output is the basic requirement of any program/system. The java.io package deals with operations related to reading/writing to console, reading/writing to files, etc It contains many classes related to I/O operations for different types of read/write requirements. Java supports two kinds of I/O = Byte oriented = Character oriented (Unicode is of 2 bytes) Stream based I/O [stream is inked to a physical device by the lava /0 system, + Astream can be considered asa pipe through which data flows. The stream is an abstraction that either produces of consumes information All steams behave in same manner, even ifthe associated actual physical devices differ. ‘Advantage of stream /0 Is that one stream can be connected with another compatible stream exon ERSRERE functors of bur stream canbe used Topics Concepts of /0 in Java + Properties of file or directory + YO classes + Character streams were not present in original version of ~ inputstean/ourpusiear = seodoriee Binary /0 and Text YO Reading from keyboard and writing to console Reading from file and writing to file Tokenizing input Use of Input/Output in GUL application Stream Stream is a continuous flow of data — Eg, water flowing through a water pipe, A program can read from or write to an external entity (file, keyboard, network, etc.) through a stream Output operation Input operation teat) teenth Stream based I/O In Java, sreams for both types of data have been defined: byte stream classes and character stream classes. = InputStream and OutputStream class hierarchies for byte oriented = Reader and Writer class hierarchies for character oriented (ava 1.0), but were added in Java 1.2. CCharacter streams use Unicode, ‘At the lowest level, all /O is still byte-oriented, File class + Itprovides machine-independent abstraction for files, directories, nd path names + Itdescribes the properties ofa file itself, not the file content = permissions, = time, date, = directory path, ~ to navigate subdirectory hierarchies + Deals with most of the machine-dependent complexities of files and path names = Windows: separator is\, but since tsa special character ‘we need to write \\ — Unix/tinux: separator i /. But it works on Windows also File class: methods + publicjava.lang string getNamet}; + public java.lang String getParent) + public java.io.File gtParentFlel); + publcjava.lang.string petPath(}; + public boolean isAbsolute() + publicjava.lang String exAbsolutePath\); + public java.io.File getAbsolutetilel); + publicjava.lang String getCanonicalPath() throws jvaio.}OException; + publicjava.iaFile getCancnicalFile() throws javaio IOException; File class: methods + publicboolean createNewfile() throws java.ioOException; * public boolean deletel) + public void deleteOnexit); + public java.lang.String list); + public java.lang String list{java io. FllenameFlter); + public java.io.File] stiles); + public java.io.File] istFiles(iavaio.FlenameFiter); + public java.io.File} listFiles(ava.io.FileFiter); + publicboolean mic); + publicbootean micirs(); + publicboolean renameToljavaio.ie}; File class and constructors + public class java.io.File extends java.lang.Object, implements java.io.Serializable, java.lang.Comparable + Constuctors — File(string cirectoryPath) — File(string cirectoryPath, String filename) ~ FileFile cirOb, String filename) ~ File(URI urobj) File class: methods + publicjava.netURLtoURLI) throws java.net. MalformedURLException; * public java.net URI toURI(; + publicboolean cankead!); + publicboolean canWrite(); * public boolean exists); + publicboolean isbirectory); + public boolean isle); + publicbootean ishidden(); + publiclong lastModitied); + publiciong length) File class: methods + publicboolean setlastMadifed{long): + public boolean setReadOnly() + publicboolean setWritable{boolean, boolean); + publicboolean setWritable(boolean); + publicboolean setReadable(boolean, boolean}; publicboolean setReadable{boolean); + public boolean setExecutable(boolean, boolean; publicboolean setExecutable(boolean); publicboolean cantxecute(); File class: methods + public static java.io File) listRoots) + publiclong getTotalSpace(; + publiciong getFreeSpace(); + public long getUsableSpace(; + public static java.io.File createTempFile(javalang String, java.lang.String, javaio.ile) throws java.io.|OException; + public static java.io File createTempfileljava lang String, javalang.String) throws java.io Exception; + publicint compareToljava.ioFile}; * public boolean equals(ava lang Object} Program: FileProperties System out printin{.canWrite) ? "is writeable” : "is not writeable") System .out.printin{i.canRead()? "i readable" : is not readable") System out.printin('is "+ (FLisDirectory() 7": "not" +" directory"); System out prntin(f.isFle]?*'s normal file”: "might be a named pipe"); System out printin{f.sAbsolutel)?"s absolute”; “isnot absolute"); Program: FileProperties + Running the program Program: FileProperties impor java.io le; impor java.ui.0ate; dass FlleProperties public static void main(String! args File 1 = new Fle(‘FlePropertiesjaa"); Fle 2 = new Fle("P\\reading materils\\Subject\\Core sava\\programs\io\\FleProperties ova); ‘ystem.outpintin Fle Name: "+f. getName) Sjetem out pinthn Path: + #1 gtPath) System.outpintln( Absolute Path: "+ .getAbsolutePath(); System out pintin(Parent:" + 1 getParent) Spstem out prnin(L xsl)? Measis"* "doesnot exist"; Program: FileProperties System out printi"File last mocified: * = new Date(f1.astModified()}; System .out.printin("ile size:" + f.length()+" Bytes"); System out println("2 Parent: + f2.getParent|)}: ) Stream classes + InputStream ang OutputStream are designed for byte + Reader and Writer are designed for character streams. ‘+ The byte stream classes and the character stream classes form separate hierarchies. + Which one to use? We should use the character stream classes when working with characters or strings, We should use the byte stream classes when working with bytes or other binary objects Predefined Streams Class hierarchy: InputStream + System.in ~ Standard input, keyboard by default = Itisan object of type InputStream + System.out = Standard output stream, console by default ~ ttis an abject of type PrintStream + Systemerr — Standard error, console by default = Itisan object of type Printstream Class hierarchy: OutputStream RandomAccessFile Class hierarchy: Reader Class hierarchy: Writer Ailewriter InputStream and OutputStream + InputStream is an abstract class that defines Java’s model of streaming byte input. It implements the Closeable interface, OutputStream is an abstract class that defines streaming byte output. It implements the Closeable and Flushable interfaces, + Most of the methods of these two classes throw lOException, Names of classes * Based on source ar destination of data —File — ByteArray Operation —CharArray (input) Source String (Tin) — StringBuffer — Object Name of clas: ileinputSteam InputStream and Reader + InputStream isan abstract cass that defines streaming byte input + Itimplements Closeable interface and al ofits methods can throw IOException. public abstract int real) throws IOException = public abstract int reaefoyte bf} throws IOException ~ public abstract vod lose} throws 102xcepion = publicabstract int avaable (} vows IOException + itis avaiable only in npttrenm notin Render = public long skipilong bytes) throws IOException + Both read methods are blocking, in no datas avaliable ~ Itreturns how many bytes are read ~ Retuens-1 when theres end of data (EOF) Reader and Writer + Reader is an abstract class that defines Java's model of streaming character input. It implements the Closeable and Readable interface. + Writer is an abstract class that defines streaming character output. It implements the Closeable, Appendable, and Flushable interfaces, + Most of the methods of these two classes throw lOException, Names of classes + Based on the way input or output operations are performed on data = Filter — Piped Existing stream Sp. operation — Buffered (input) (Buffered) = LineNumber steam = Pushback Name of css: uttereah = pata lame of class: BufferedInputstveam Specialized functions = StreamTokenizer — RandomAccessFile OutputStream and Writer (OutputStream is an abstract class that defines streaming byte output + Itimplements Closeable and Flushable interfaces and all of ts ‘methods return void and can throw lOException, {As there is no return value (return type is void), status of ‘method cal is determined based on whether exception is thrown or not. = public abstract void wrte(int b) throws IOException — public abstract void write(bytef | buf] throws !OException = public abstract void close() throws lOException — public abstract void flush() throws IOException + itlers the bate Le, sens the deta tothe stream, Processing External Files Reading input froma file —FileinputStream + Flleinputstrear(Strng filePath) + FilelnputStream(Filefleobj) = Both can throw FileNotFoundException — Methods: mark() and reset() are not overridden by this class so its use will result in lOException Program: Reading a file import java.io.Fileinputstream: import java.io JOFxception; ass FileRead public static void main(String] args) throws IOException{ ifargslengthl=2) system out.prin sage: java FileRead inputFileName"}; System ext(0); Running the Program: Reading a file Processing External Files + Writing toa file —FileOutputStream + FlleCutputstream(strng fiePath) + FlleOutputstreamiilefileOb)) + FileOutputstream(String flePath, boolean append) + FileOutputStreamilefileObj, boolean append) — Constructors can throw FileNotFoundException or SecurityException —If append is true, the file is opened in append mode. Program: Reading a file (cont...) Filelnputstream fis=new FileinputStream(args{O}) see=fis available(); System.out printn("The file: "+args[O}+" has “sizes bytes"); ‘ystem.out.printin("The content of file"); forint i=0;fcsizes+-) System out prnt((charfis. read} Program: Reading a file (without typecast to char) + Type casting to chars important forlint-Ojesieie) System out print((charf's.tead) + we do not typecast, then what will happen? forlintisdjiesae;i+) System out prints read); Program: Reading a file (without typecast to char) § Cvinonvontend = Program: Using seek() to jump file read pointer (cont...) size=fis. available); bytel] butfer=new byte[10]; ‘System.out.printin("The file: "+args[O]#" has “4sizee" bytes"); System.out.printin("The fist 10 bytes of file"; fisreadibutter) forlinti0jc1Oyi++) System out print{(char}bufferi}; ‘system.out.printin() Running the Program: Using seek() Program: Using seek() to jump file read pointer import java.io FileinputStream: import java.io JO€xception; cass FilePortionfiezd{ public static void main(String] args) throws lOException{ iffargslengthl=1} System out printin("Usage: java FileRead InputFlleNam System .ext(0); FllelnputStream fis=new FileinputStream(args(0) Program: Using seek() to jump file read pointer (cont...) System. out.printin("The ast 10 bytes of ile"; fis skiplsize-10-10); fisreadibutfer) forlintidsichOyie+) System out prnt((char}oufferi); Program: file copy command import java.io FileinputStream: import java.io.FileOutputStream; import java.io.File; import java.io JOFxception; import java.io FleNotFoundéxception; cass FileCopyt public static void main(String] argsit Filelnputstceam fisznull; FleOutputstream fos-null byte readByte; Program: file copy command (cont...) ifargs lengthl=2) System .out.printin("Usage: java FileCopy SourceFileName DestFileName"); System exit(0); wy fisenew FileinputStream{new FileargstOny: fereate file output stream ifthe fle does not exist File outFle=new Filelares(LI}; Program: file copy command (cont...) catch(FileNotFouncException el{ System out printin("File:"sargs[O]+" not found"); catch(lOException e)/ System out prntin(e.getMessage(); finally, wl ifist=null fis.close(); i{fost=null) fos.close) Running the Program: file copy Program: file copy command (cont...) iffoutFite exist) ‘System .out printn( "File: “sargs(t]#" already exists"; return; , else fosznew FleOutputStream(args(t}); aot readByte = (byte) fs.ead); {os.writelreadsyte}; while(readByte!=-1); Program: file copy command (cont catch(lOException eM) Running the Program: file copy Program: writing using character stream import java.io importjavaio.le; tion; class CharacterOrientedWritet public static void main(Stringl|args}throws |OFxception( Flewriterfw=null; ifargs.length!=2} System out printin("Usage: java CharacterOrientedWrite textfileName.tat”) System .ext(0); Program: writing using character stream (cont...) Uorting data as text fw=new FileWrterfile); fwwrite("Hello" if(fwlenull) fueclose Array Streams + InFileinputstream (and FileReader) and FileOutputStream (and FileWriter) are source and destination of input and output operation, respectively. Similatly, Java allows ByteAvray and CharArray as source and destination of input and output operations. = Input + Bycoarrayinpustream + chararrayReacer = Output + BycenrrayOurputstream + Chararraywriter Program: writing using character stream (cont...) File filesnew File(args[0]); ifffilecexists())( sytem .outpritn("Te file: “+argslol+ * already exists ‘delete it, and rerun the program’); System exit(0); Running Program: writing using character stream Array Streams + What is the use of these streams? — ByteArcayinputStream implements both mark() and reset = We can read same input multiple times. = £4, while transferring fle content from one machine to another in network + We can read content from a fle ané write ito a byte buffer (Le, array} on source machine + Then transfer the buffer at once to another machine. Array Streams Constructors ~ Sitter nputseeamtby | input8ytteray) = Bytedrayinputseamtbye | input8yedoray nt start, int ues) ~ Chartrayeade(carlJinputChaeteray) ~ Chartrayeader(car | ingutChavtray, instant muchas) ~ Syervrayoutpustreomi) ~ 2ytetvrayOutpusteemine numByses), = chartrayrtert = ChararayWter(t maracas) When we use default constructors for ByteArrayOutputStream and CharArrayWr slee is 32 bytes, The buffer size is increased automaticaly if needed, default butter Program: read byte array twice (cont...) whilel(cbais.read{))!=-1){ System.out.print((char}els bais reset ‘systemout priatin( wihile((e=bais.read{)}!=-1){ System out print{CharactertoUpperCase((char)e) ) Filter Streams Basic input or output stream provides methods to read or write byte or characters. However, filter streams can filter bytes or characters for some purposes. = Eg, Instead of reading individual byte or character, we may want to read integer, double, or float We should use FilterinputStream and FilterOutputStream to filter bytes. We should use BufferedReader and PushbackReader to filter characters when we need to process strings. Program: read byte array twice import java.io.ByteArraylnputStream; import java.io JO€xception; cass ByteArrayResding{ public static void main(String] args) throws |OException( String nputString="Information Technology’: bytel] b=ingutString.getBytes(); ByteArrayinputStream baisenew ByteArrayinputstream(b inte; Running the Program: read byte array twice Filter Streams + FiterInputStream and FitterOutputStream are abstract classes, We use their subclasses for our purposes + Subclasses of FilterinputStream Datalnpetstream ‘Allows reading of all primitive data Butferedinputstream Reads data from the buffer, reads/loads data {rom the underiying stream f needed LineNumberinputstream Keeps rack of how many ines are read PushbackinputStream Allows single byte look-ahead. After reading a byte, ican be pushes back to the sear Filter Streams + Subclasses of FilterOutputStream DataOutputstream Allows wrting of al primitive dat in binary formats BufferedOurputStream Outputs othe buffer frst and then ourputs to the stream, if required. We can use flush) method to wrt the content ofthe buffer to the actual stream Printstream ‘Allows writing of al primitive types in unicode format, Reading Console Input + BufferReader supports a buffered input stream, for which constructor is — ButferecReader{Reader inputReader) + InputStreamReader can convert bytes into characters. Constructor is ~ InputStrearnReader{inputStream inputstream) + Thus, keyboard input is performed using the following code BufferedReader br=new SufferedReader(new InputStreamReader(Syster.in}; String inputlinebrreadline() Program: reading console input (cont...) systemoutprint"Entra floating point umber = float F Float parseFloat(brceadLine(}.rim()}; System.out printin( "Entered number is") Reading Console Input + Indava 1.0, console input was possible with use of byte stream, as character stream was not present. + Tough, byte stream can be used to ead console input, itis not recommended, + Rather, we should use character oriented stream for console input. ‘+ We can read from console using Systerin, which is byte stream oriented, Program: reading console input import java.io.BufferedReader; import java.io.InputStreamReader; import java.io 1O€xception; cass Readinputl public static void main(String] args) throws IOException BufferedReader br=new ButferedReader(new InputstrearnReader(Syster.in}; ‘system.out print("Enter an integer number int isintegerparseint(brreacLine( trim(); ‘ystem.out printin("Entered number is") Running the Program: reading console input PrintStream & PrintWriter + Use of system.out to write tothe console is recommended ‘mostly for debugeing purposes or for sample programs. + For real-world programs, use of PrintWriter stream is recommended, ~ Printwrter(Outpusstream outpurstream, boolean fushOnNewiine) ~ Hf flushonNewlie is true, fushing automaticaly takes place. tf false, fishing sot automate + PrintWriter supports the print() and printin() methods forall types including Object. = Han argument snot simple type ean obec) the Printer methods cal te yet testing) meinad Program: writing data as text import java.io.Print Writer, import java.io.FileOutputStream; import java.io.File; cass TextWritel public static void main(String] args}throws 1OException( Printwriter pwenull ifargslength!=2} System out prntin("Usage: java Textwrite textfileName tt") System ext(0); Program: writing data as text (cont...) I rting data 25 text pw-new PrintWriterinew FileOutoutstreamiile); forint i0ie10si+4) ppuprint{{int)(Math.random(}*1000}+""); iffew!=null) closet) PrintStream & PrintWriter + To write to the console by using a PrintWriter, specify System.out for the output stream and flush the stream after each newline, + PrintWriter pw = new PrintWriter(System.out, true}; Program: writing data as text (cont...) Fic file=new File(argsi0}: ifflecenstsOt System out prntin("The ile: “+args[O]+ already exsts,"+ “delete it, and rerun the program’); System .exiti0); Running Program: writing data as text PrintStream & PrintWriter: formatted output + Formatting was added in J2SE 1.5, + Useful methods in PrintStream class = Printstrearm print(sting string, Object res) ~ Printstream prnt(Strngfntstrng, Object. ars) ~ Printstear freat{strng emtsving, Object] aes) = Protstrear formatting mtsrng, Object. gs) + Useful methods in Print Writer class = PrintWrterpintstring ftstring, Object args) = Printriter prittString ftstring, Objet. ares) ~ PrntWrter format(strngftrng, Object] args) = Printrter format(strngfntstrng, Object. args) PrintStream & PrintWriter: formats + HF = Floating point number + %2F — Two dats after decimal point + %.2F = One space ater %: to align postive number with negative number + %,26 = Format number with cornma Running the Program: displaying formatted data PrintStream & PrintWriter: formats + 3d = integer number + Sed = alsplay +n from of postive number, to align + md ~ splay negative as bracketed, instezd of negative + %d ~ One space between % and dt align with negative numbers + 8d ~ Print integer number inthe spectiog with, right justifiee + 05d = Print integer number inthe specified with, with leading zeros Program: displaying formatted data ass FormattedWte| publi stati void main(Strinl] aril {Formatting integer data System.out.printf"%d %(¢ Hrd KOSd MSd\n"9,-9,9.9.9); system. out print("% dn 100); System.outprint!("4d\n 100); /Formatting floating point data System. our printt("%.2Ain' 9999.99}; System.outprint{(°%.2A\n, 9999.98); System.out printf'%.2F\n" System. out printf, 200" Data Streams ‘+ The data streams (DatalnputStream and DataOutputstream} read and write Java primitive types in a machine-independent {ltle-endian or big-endian) fashion. ~ Itis possible to write binary file on one machine and read iton another machine having different 0S or platform. + Datainputstream extends FiterinputStream and implements Datainput interface + DataOutputStream extends FilterOutputStream and implements O2taOutput interface ‘+ DatainputStream and DataOutputStream are generally used ‘0 avail facility specified by Datalnput and DataOutput interfaces, Methods of Datalnput + public byte readByte() throws IOException + public short readShort() throws IOException + public int readint() throws !OException + public long readLong() throws IOExceation + public float readFloat{) throws IOException + public double readDouble() throws IOException * public char readChar() throws IOException + public boolean readBoolean() throws IOException + publie String readLine() throws IOException + public String readUTF() throws IOException How data streams are used? ‘+ The data streams are often used as wrappers on existing input or output streams (e.g, files) to filter data in original stream, = Data Input +public DatalnputStreamiInputStream instream) — Data output + publi DatsOutpustream(Outputstream outStream) + Examples DatalnputStream infile=new DatalngutStream|new FileinputStreamn(t. data) DataOutputstream ousFlesnew DatsOu TileOutputstrenm(“out ta") Program: binary read-write (cont...) ifargs.iength!=1 system out prin BinaryReadWrite dataFileName.dat"}; System .ext(0); sage: javo File file=new File(args(0); ifflle.exstsO System out printin("The file: "+args[0|+ already exists,"+ ‘delteit, and rerun the program’); System.ext(0); Methods of DataOutput + public void writeByteintb) throws IOException + public void writeShort{ints) throws lOException + public void writeChar(int¢) throws lOException +public void writelnt(nt) throws lOException + public void writetong(long |) throws IOException + public void writeFloat{fioat f) throws !OException + public void writeDouble(double a) throws IOException + public void writeBytes{Strings) throws IOException +public void writechars(strings) throws IOException + public void writeUTF(String s) throws IOException Program: binary read-write import java.io.Datainputstream; import java.io. DataOutputstream; import javaio.1OException; import javaio.FleNotFoundException; import java io FilelnputSteeam; impor java.io FleOutputStream; import java.io.File; class BinaryReadWrite( public static void main(String} args}throws IOException{ DatainputStream dis=null; DataOutputstream éos=null Program: binary read-write (cont...) Inwrting data wl 6 FileOutputstream(fie)); forfinti0;:<20;i"4) jew DataOutputstream(new dosavritelnt(ine(Math.randomi)*1000)); catch(lOException System out prntin(e.getMessage(); Program: binary read-write (cont...) finally, tw if(dost=null) dos.close(); , catch(lOException e}f) Program: binary read-write (cont...) finally trl idos!=nul) dos.close(); ) catch(lOException eM) Running the Program: binary read-write Program: binary read-write (cont...) 1/Reading data trl dissnew Datalnputstream(new Feinputstrear(file)); forlint i-0,<20;i¢4) ‘System.out.print(dis.readint(}+""); catch(FileNotFoundException e}{ System out prntin(e.getMessage(); ‘catch(lOzxception e}i System out printin(e.getMessage(); Running the Program: binary read-write Stream Tokenizer: Parsing Text files + StreamTokenizer class provides facility of tokenizing a file + streamTokenizer generates tokens (separated words) and allows to get one at a time. ‘StreamTokenizer class has three variables = int ttype + Indicates current token type = double nval + Gives the value of current token iit is numberfinteger or floating point) = String sval ves the string valu if the token is nota number Stream Tokenizer: Parsing Text files + StreamTokenizer constants = publicstatic final int TT_EOF; = public stati final int TT_FOL; — public static final int TT_NUMBER; = publi static final int TT_WORD; + Method to go to the next token = public int nextToken) + How to use? ifsttype==st.7T_NUMBER) double value=stnval Program: parsing a text file (cont...) double su 00; hile (t=st.nextTokent)}!= TT EOF if(t=st.77_NUMBER){ System out.printinst.aval sume=st.nval ‘System out.printin(st.svalt" is not a number"); } System out prntin("Sum of above numbers is "*sum}; Running Program: parsing a text file Program: parsing a text file import java.io." ass TokenizeFil{ public static void main(String] args)throws Exception{ Ifargs.lengthi=2)f System.out printn("Usage: java Textrite textfleName.tet"); system.exit(0); ) File!nputStream fs-new FlleinputStream(args{0l); StreamTokenizer st=new StreamTokenizer(s}; Compiling Program: parsing a text file + Constructor taking InputStream is deprecated + We can use the following FileReader frenew FileReader(args(0l); StreamTokenizerst=new StreamTokenizer{; Random Access File +All of the streams used so far are either read-only or ‘write-only streams. + Those streams are sequential — Every time there is change in data, we need to recreate the file and need to rewrite the whole dats. — RandomAccessFile supports positioning requests (we can position the fie pointer within the fle) + RandomAccessFie class allows both reading and writing = Its not derived from InputStream or Outputstream = Implements Datalnput and DataOutput interfaces, and it also implements Closeabie interface. Random Access File * Constructors —RandomAccessFile(FilefileObj, String access) throws FileNotFoundException —RandomAccessfile(String fileName, String access) throws FileNotFoundéxception + Examples — new RandomAccessFile(“result. data’, “rw"}; Program: random access import java.io.RandomAccessFile; import java.io.!Otxception; class RandomAccess{ public static void main(String|] args}throws. RandomAccessFile raf= RandomAccessFile('testtxt","1W"); rafseek(s); rafwritechar(W'); raf skipBytes(3}; rafwwritechar(H"); Exception( Program: Use in GUI application, notepad import java.io FilelnputStream; import java.io.InputStreamReader import java.io.BufferedReader; import java.io.!OException;, import java.awt-Frame; import java awt TextField; import java.awt Textarea; import java.awt Pane! import java.awt.Button; import java.awt.event.ActionListener; import java.awtevent ActionEvent; Random Access File + Useful methods = void seek(long newPos) throws IOException = void skipBytes{int skip) throws lOException + Skips spectid numberof bytes relative tothe current postion — long getFilePointer(} throws IOException — long length) \OException = void writeChar(int v) throws !OException + Wites character as two byte Unicode = void writeUTF(String s) throws IOException — void setLength(iong length) throws IOException * Use to shorten ot lengtnen the fle Running Program: random access Program: Use in GUI application, notepad (cont...) sad extends Frame implements Actonlistener{ Textarea ta; TextFeldt Button by public static oie main(String ares Frame fnew Notepac); ) public Notepad Super("Notepac"): tasnew Tertrea(); tfenew Toxteld(35); benew 8utton("show"); Program: Use in GUI application, Program: Use in GUI application, notepad (cont...) notepad (cont...) Panel p=new Panel(); public void actionPerformed(ActionEvent ae){ pada Fllnputstream fn paddlb); BufferedReader br=nul; baddActionListener(this) String s=ae-getActioncommandl); add{ta) add("South"p); setSize(800,600); setVisible(true; new trrequestFocust); FilelnputstreamittgetText() trim( setVisibe(tr] brenew ButferedReader(new etvesble(tue; InputstreamReadert(}); ‘ boolean frst-true; Program: Use in GUI application, Program: Use in GUI application, notepad (cont...) notepad (cont...) whilelstbrceadtint) =u catehitxeption oe) ified System out prititoe); ta.appensts; ' fistfalses fioalv » item eso tt ta.appendt"n"str fase: s » ) catch(Excepione) ta.setCaretPositionO} Sytem.out print); sarequestFacus( : , 2? Program: Use in GUI application, Running Program: Use in GUI notepad (cont...) application, notepad ) fl Running Program: Use in GUI application, notepad

You might also like