Anda di halaman 1dari 56

Concepts of Streams

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.

There are two types of streams in Java


Input stream

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

Byte Stream Classes


Input Stream Classes
Output Stream Classes

Reader Classes

Memory

File

Pipe

Memory

File

Pipe

Byte Stream Classes


These classes have been designed to provide functional features for

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.

Byte Stream Classes


Summary of InputStream Methods

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

Byte Stream Classes


It is to be noted that the class DataInputStream extends

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

Byte Stream Classes


Summary of OutputStream Methods Method
write() write (byte b[], int n, int m) close() Flush()

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

Character Stream Classes


They are used to read and write 16-bit Unicode characters. There are

two kinds of Character Stream called

reader stream classes

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.

Hierarchy of Reader Stream Classes


object

Reader
StringReader

BufferedReader
CharArrayReader

PipeReader
FilterReader
PushbackReader

InputStreamReader FileReader

Character Stream Classes


Writer Stream Classes: These classes are designed to perform all output operations on files. The writer stream classes are designed to write characters. The writer class is an abstract class which acts as a base class for all other writer stream classes. This base class provides support for all output operations by defining methods that are identical to those in OutputStream class.

Hierarchy of Writer Stream Classes


Object
Writer
BufferedWriter PrintWriter
StringWriter FilterWriter

PipeWriter
CharArrayWriter

OutputStreamWriter

FileWriter

Program 1 (Reading /Writing characters)


import java.io.* class copyc { public static void main(String args[]) { File infile=new File(input.dat); File outfile=new File(out.dat); FileReader ins=null; FileReader outs=null; try { ins=new FileReader(infile); Outs=new FileWriter(outfile);

Program 1 (Reading /Writing characters)


int ch; while(ch=ins.read())!=-1) { outs.write(ch); }} catch(IOException e) { System.out.println(e); } finally { try { ins.close();

Program 1 (Reading /Writing characters)


outs.close(); } catch(IOException e) { } } } }

Program 2 (Writing Bytes)


import java.io.*; class writeb { public static void main(String args[]) { byte cities[]={D,E,L,H,I\n,M,A,D,R,A,S}; FileOutputStream outfile=null; try { outfile =new FileOutputStream(city.txt); outfile.write(cities); outfile.close(); }

Program 2 (Writing Bytes)


catch(IOException ioe) { System.out.println(ioe); } } }

Handling Primitive Data Types


What is Data Stream?
Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. If we want to read/write the primitive data types , we use filter classes on existing input and output streams to filter data in the original stream. The two filter classes used for creating data streams for handling primitive types are DataInputStream and DataOutputStream.

Handling Primitive Data Types


A data stream for input can be created as follows: FileInputStream fis=new FileInputStream(infile); DataInputStream dis=new DataInputStream(fis);

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(); }}

Other Stream Classes


Object Streams: It is also possible to perform input and
output operations on objects using the object streams. The object streams are created using the ObjectInputStream and ObjectOutputStream classes. This process is called Object Serialization.

Piped Streams: If we want to communicate and


exchange the data between threads, we use piped streams. The write thread sends data to the read thread through a pipeline that connects an object of PipedInputStream to an object of PipedOutputStream.

Other Stream Classes


Pushback Streams: The pushback streams can be used
to push a single byte or character back into the input stream so that it can be read. These streams can be created by PushbackInputStream and PushbackReader. This is commonly used with parsers.

Filtered Streams: Java supports two classes called


FilterInputStream and FilterOutputStream to create input and output streams for filtering input/output in a number of ways.These streams known as Filters, sit between an input stream and an output stream and perform some optional processing on the data they transfer.

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

Delegation Event Model


DEM: Version 1.1 of the JavaTM platform introduced a new
delegation-based event model in AWT in order to: Provide a more robust framework to support more complex java programs.

Design Goals:The primary design goals of the new model in the


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

Delegation Event Model


The modern approach to handling events is based on delegation event model which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event.Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is separated from the user interface logic A user interface element is able to delegate the processing of an event to a separate piece of code.

Delegation Event Model


In the delegation event model, the listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them. This is more efficient way to handle events than the design.

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.

Event Sources: A source is an object that generates an event. This


occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event .Each type of event has its own registration method.

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 Listeners: A listener is an object that is notified when an event


occurs.

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

Event Listener Interfaces


Interface
ActionListener
AdjustmentListener ComponentListener FocusListener KeyListener MouseListener

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.

AWT Classes and Controls


The AWT classes consist of Component, Container, and Panel.

Component: At the top of the AWT hierarchy is the Component


class. Component is an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. It defines over a hundred public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting. A Component object is responsible for remembering the current foreground and background colors and the currently selected text font.

AWT Classes and Controls


Container: The Container class is a subclass of Component. It
has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container (since they are themselves instances of Component). This makes for a multileveled containment system.

Panel: The Panel class is a concrete subclass of Container. It


doesnt add any new methods; it simply implements Container. A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the superclass for Applet. When screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar, menu bar, or border.

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).

AWT Classes and Controls


The AWT supports following types of controls: Labels Push Buttons Check Boxes Choice Lists Lists Scroll Bars Text Editing These controls are subclass of Component

AWT Classes and Controls


Adding and Removing Controls
Use add() method which is defined by Container class. //

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) {

g.drawString (msg, 10, 100);


}

Anda mungkin juga menyukai