Input refers to the flow of data into a program and output means the
flow of data out of a program. Input to a program may come from the keyboard, the mouse, the memory, the disk, a network. Similarly, output from a program may go to the screen, the printer. These devices share certain common characteristics such as unidirectional movement of data and support to the sequential access to the data. This is illustrated in the following figure: Java uses the concept of streams to represent the ordered sequence of data, a common characteristic shared by all the I/o devices. A stream represents a uniform, easy-to-use, object-oriented interface between the program and I/o devices.
Concepts of Streams
Sources Keyboard Mouse Destinations Screen printer
Java Program
Memory Disk Network memory Disk Network
Concepts of Streams
A stream in Java is a path along which data flows. It has a source and a
destination. Both may be physical devices or programs The concept of sending data from one stream to another has made streams in java a powerful tool for file processing. We can build a complex file processing sequence using a series of simple stream operations. For example, we can use one stream to get raw data in binary format and then use another stream in series to convert it to integers.
Output stream
Concepts of Streams
Input Stream: This stream extracts i.e. reads the data from the source
and sends it to the program. Output Stream: This stream takes the data from the program and sends it to the destination.
Input Stream reads
Source
Program
( READING DATA INTO A PROGRAM )
Program
writes Output Stream
Destination
(WRITING DATA TO A DESTINATION)
Stream Classes
The java.io package contains a large number of
stream classes that provide capabilities for processing all types of data.These classes may be categorized into two groups: Byte Stream Classes: that provide support for handling I/o operations on bytes. Character Stream Classes: that provide support for managing I/o operations on characters.
Stream Classes
Java Stream Classes Character Stream Classes Writer Classes
Reader Classes
Memory
File
Pipe
Memory
File
Pipe
creating and manipulating streams and files for reading and writing bytes. Since the streams are unidirectional, they can transmit bytes in only one direction and therefore Java provides two kinds of Byte Stream Classes:
Input Stream Classes: The classes that are used to read 8-bit
bytes include a super class known as InputStream and a number of subclasses or supporting various input-related functions. The super class InputStream is an abstract class and we can not create instances of this class. The InputStream class defines methods for performing input functions such as Reading bytes Closing streams Finding the number of bytes in a stream.
Method
read() Read (byte b[],int n, int m) available() skip(n) reset() close()
Description
reads a byte from the input stream reads m bytes into b starting from nth byte gives number of bytes available in the input skips over n bytes from the input stream goes back to the beginning of the stream closes the input stream
FilterInputStream and implements the interface DataInput. Therfore, the DataInputStream class implements the methods described in DataInput in addition to using the methods of InputStream class. Output Stream Classes: These classes are derived from the base class OutputStream. It is also an abstract class. The several subclasses of the OutputStream can be used for performing the output operations. They include methods that are designed to perform the following tasks: Writing bytes Closing streams
Description
writes byte to the output stream writes m bytes from array b starting from nth byte closes the output stream flushes the output stream
and write stream classes. Reader Stream Classes: These classes are designed
to read character from the files. Reader class is the base class for all other classes. These classes are functionally very similar to the input stream classes except input stream use bytes while reader streams use characters. Reader classes can perform all the functions implemented by the input stream classes.
Reader
StringReader
BufferedReader
CharArrayReader
PipeReader
FilterReader
PushbackReader
InputStreamReader FileReader
PipeWriter
CharArrayWriter
OutputStreamWriter
FileWriter
These statements first create the input file stream fis and then create the input data stream dis. These statements basically wrap dis on fis and use it as a filter. Similarly, the following statements create the output data stream dos and wrap it over the output file stream fos.
FileOutputStream fos= new FileOutputStream(outfile); DataOutputStream dos=new DataOutputStream(fos);
Program
import java.io.*; class rw { public static void main (String args[]) throws IOException { File primitive=new File(p.dat) FileOutputStream fos=new FileOutputStream(primitive); DataOutputStream dos=new DataOutputStream(fos); dos.writeInt(1999); dos.writeDouble(375.85); dos.writeBoolean(false); dos.close(); fos.close();
Program
FileInputStream fis=new FileInputStream(primitive); DataInputStream dis=new DataInputStream(fis); System.out.println(dis.readInt()); System.out.println(dis.readDouble()); System.out.println(dis.readBoolean()); dis.close(); fis.close(); } } Output: 1999 375.85 false
Program
import java.io.*; class sequence { public static void main (String args[]) { FileInputStream file1=null; FileInputStream file2=null; SequenceInputStream file3=null; file1 = new FileInputStream(text1.dat); file2 = new FileInputStream(text2.dat); file3=new SequenceInputStream(file1,file2); BufferedInputStream inBuffer=new BufferedInputStream(file3); BufferedOutputStream outBuffer=new BufferedOutputStream(System.out);
Program
int ch; while((ch=inBuffer.read())!=-1) { outBuffer.write((char)ch); } inBuffer.close(); outBuffer.close(); file1.close(); file2.close(); }}
StringTokenizer
The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments. The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis. An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnDelims flag having the value true or false: If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters. If the flag is true, delimiter characters are themselves considered to be tokens. A token is thus either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.
StringTokenizer
Method
Boolean hasMoreTokens() String nextToken()
Description
Returns true if one or more tokens remain in the string and returns false if there are none. returns the next token as a String
int countTokens()
the method determines the number of tokens left to be parsed and returns the result
The following is one example of the use of the tokenizer. StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } prints the following output: this is a test
AWT are the following: Simple and easy to learn Support a clean separation between application and GUI code Facilitate the creation of robust event handling code which is less error-prone (strong compile-time checking) Flexible enough to enable varied application models for event flow and propagation
Events
Events: An event is an object that describes a state change in a source. It
can be generated as a sequence interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list.
Here is general form: public void addtypeListener (TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. e.g. the method that registers a keyboard event listener is called addKeyListener(). The method that registers a mouse motion listener is called addMouseListener(). A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form is
public void removeTypeListener(TypeListener el) Here, type is the name of the event and el is a reference to the eventlistener.
Event Classes: The classes that represent events are at the core of
Javas event handling mechanism. They provide a consistent, easy-touse means of encapsulating events. The package java.awt.event defines several types of events that are generated by various user interface elements. The list of event classes is as follow:
Event Class
ActionEvent
AdjustmentEvent ComponentEvent ContainerEvent FocusEvent InputEvent
Description
Generated when a button is pressed, a list item is double-clicked or a menu item is selected. Generated when a Scroll bar is manipulated Generated when a component is hidden, moved resized or becomes visible Generated when a component is added or removed from container. Visible generated when a component gains or losses keyboard focus. Abstract super class for all component input event classes.
Event Class
KeyEvent
MouseEvent
Description
generated when input is received from the keyboard Generated when mouse is dragged, moved, clicked, pressed or released generated when a window is activated, closed, deactivated
WindowEvent
Description
Defines one method to receive action events Defines one method to receive adjustment events Defines four methods to reorganize when a component is hidden, moved, resized Defines two methods to reorganize when a component gains or loses keyboard focus. Defines three methods to reorganize when a key is pressed, released or typed. Defines five methods to reorganize when the mouse is clicked, enters a component, exits a component is pressed or is relesased.
FRAMES
After the applet, the type of window you will most often create is
derived from Frame. You will use it to create child windows within applets, and top-level or child windows for applications. As mentioned, it creates a standard-style window. Frame supports these two constructors: frame( ) frame(String title) The first form creates a standard window that does not contain a title. The second form creates a window with the title specified by title. Notice that you cannot specify the dimensions of the window. Instead, you must set the size of the window after it has been created.
FRAMES
Setting the Windows Dimensions:
The setSize() method is used to set the dimensions of the window. Its signature is void setSize (int newWidth, int new Height) void setSize (Dimension new Size) The new size of the window is specified by newWidth and newHeight. The getSize() method is used to obtain the current size of a window.
Hiding and Showing a Window: After a frame has been created, it will not
be visible until you call setVisible(). Its signature is
void setVisible (boolean visibleflag) The component is visible if the argument to this method is true otherwise is hidden.
FRAMES
Setting a Windows Title: If you can change the title in a frame using
setTitle() having the following form Void setTitle (String newTitle)
Closing a Frame Window: When using a frame window, the program must
remove that window from the screen when it is closed by calling setVisible(false).
add() has several forms. Component add (Component compObj) A reference of compObj is returned . Once a control has been added, it is automatically visible whenever its parent window is displayed. void remove (Component compObj) To remove all controls by calling removeAll() method.
Labels
The easiest control to use is a label and contains a string which it displays .Label defines the following constructors: (i) label() (ii) label (String str) and (iii) label (String str, int how)
The first version creates a blank string. The second version creates a label that contains the string specified by str which is left justified. The third version creates a label that contains the string specified by str using the alignment specified by how. The value of how must be one of these constants: label. left, label. right and label. center
UTTONS
Buttons A push button is a component that contains a label and that generates an event when it is pressed.
Program
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="ButtonDemo" width=300 height=200> </applet> */ public class ButtonDemo extends Applet implements ActionListener { String msg = ""; Button yes, no, maybe; public void init () { yes = new Button ("Yes"); no = new Button ("No"); maybe = new Button ("Undecided"); add (yes);
Program
add (no); add(maybe); yes.addActionListener (this); no.addActionListener (this); maybe.addActionListener (this); } public void actionPerformed (ActionEvent ae) { String str = ae.getActionCommand (); if (str.equals ("Yes")) { msg = "You Pressed Yes."; } else if (str.equals ("No")) { msg = "You Pressed No."; } else { msg = "You Pressed Undecided." } repaint ();
Program
public void paint (Graphics g) {