io package as java’s basic i/o system continue’d

22
io package as Java’s basic I/O system continue’d

Upload: harry-patrick

Post on 24-Dec-2015

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Io package as Java’s basic I/O system continue’d

io package as Java’s basic I/O systemcontinue’d

Page 2: Io package as Java’s basic I/O system continue’d

import java.io.*;

public class Read { public static void main ( String args[]) throws IOException {

BufferedReader br= new BufferedReader (new InputStreamReader(System.in)); String str; System.out.println("Enter your name"); str = br.readLine(); System.out.println("Your name is " + str); } }

Page 3: Io package as Java’s basic I/O system continue’d

//An editor example.import java.io.*;class Editor { public static void main (String args[]) throws IOException {//create a BufferedReader using System. in BufferedReader br= new BufferedReader (new InputStreamReader(System.in));String str[] = new String [100];System.out.println (“Enter lines of text.”);System.out.println (“Enter ‘Stop’ to quit.”); for (int i= 0 ; i<100 ;i++) { str[i] = br.readLine(); if (str[i] .equals (“stop”)) break; } System.out.println(“\nHere is your file:”);//display the lines for (int=0; i<0 ;i++) { if (str[i] .equals (“stop”)) break; System.out.println(str[i]); } } }

Page 4: Io package as Java’s basic I/O system continue’d

HERE IS A SAMPLE RUNC:\JBUILDER8\JDK1.4\bin\javaw-classpath"C:\WINDOWS\jbproject\

untitled40\classes;C:\...........JBUILDER8\JDK1.4\JRE\classes;C:\JBUILDER8\jdk1.4\lib\tools.jar" untitled40.Editor

Enter lines of text.Enter ‘Stop’ to quit.132046-43-346789stopHere is your file:132046-43-346789

Page 5: Io package as Java’s basic I/O system continue’d

Writing Console Output Console output is most easily achieved with print() and println() These methods are defined by the class PrintStream

which is the type of the object referenced by System.out

Even though System. out is a byte stream, using it for simple program output is acceptable.

Shortly; PrintSteam is an output stream derived from OutputStream,

And it implements the low-level method write()

write() can be used to write to the console.The simples form of write() defined by PrintStream is:

void write (int byteval) throws IOException write method writes to the file the byte specified by byteval. byteval is declared as an integer, only the low order eight bits

are written.

Page 6: Io package as Java’s basic I/O system continue’d

Demonstrating the System.out.write() method

package untitled41;

import java.io.*;

//This is a short example that uses write() to output character “1” followed by a new line to the screen

class WriteDemo { public static void main (String args[]) { int a; a='1'; System.out.write(a); System.out.write('\n');}

Page 7: Io package as Java’s basic I/O system continue’d

The PrintWriter Class

Using System.out to write to the console is possible under Java. But: Its use is recommended mostly for debugging purposes or for

sample programs such as we studied in this course

For real world programs, the recommended method of writing to the console is through a PrintWriter stream.

PrintWriter is one of the character-based classes.Using this class for console output makes easier to

internationalize the programPrintWriter defines several constructors. The one is:

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

Page 8: Io package as Java’s basic I/O system continue’d

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

outputStream is an object type OutputStream flushOnNewLine controls whether Java

flushes the output stream every time a newline (‘\’) character is output.

If flushOnNewline is true, flushing automatically takes place.

If false, flushing is not automatic

PrintWriter supports the print() and println() methods for all types including Object.

Finally:

Page 9: Io package as Java’s basic I/O system continue’d

Finally:We can use these methods in the same way as they have been

used with System.out.If an argument is not a simple type, the PrintWriter methods call

the object’s toString() method and then print the result

To write to the console by using a PrintWriter , specify System.out for the output stream and flush the stream after each newline.

For example: The fallowing line of code creates a PrintWriter

that is connected to console output:

PrintWriter pw= new PrintWriter(System.out, true);

Page 10: Io package as Java’s basic I/O system continue’d

//Demonstration of the running of PrintWriter method

import java.io.*;

public class PrintWriterDemo {

Public static void main (String args [] ) {

PrintWriter pw= new PrintWriter(System.out,

true);

pw.println (“This is a string”);

int i=-7;

pw.println(i);

double d=4.5e-7;

pw.println(d); } }

Since no there is no advantage to use PrintWriter in the simple programs.,

We can use System.out to write simple text output to the console.

The output is:untitled42.PrintWriterDemo

This is a string-7

4.5E-7

Page 11: Io package as Java’s basic I/O system continue’d

Using URLs in Applets Network Access To access a remote URL we need to establish a

network connection. Java offers several ways of doing this URL connections Sockets

In any case we need to use the java.net package in addition to applet, GUI-elements and event handling.

import java.applet.*import java.awt.*; import java.awt.event.*; import java.net.*;

Page 12: Io package as Java’s basic I/O system continue’d
Page 13: Io package as Java’s basic I/O system continue’d

Event Handling Events are supported by java.awt.event package Event model defines standard and consistent

mechanism to generate and process events A source generates an event and sends it to one or

more listeners.In this scheme, the listener simply waits until it receives an eventOnce received, the listener processes the event and then returns

Every time the user types a character or pushes a mouse button, an event occurs.

Any object can be notified of the event. All it has to do is implement the appropriate interface and be

registered as an event listener on the appropriate event source.

Page 14: Io package as Java’s basic I/O system continue’d

Events can be generated as a consequence of a person interacting with elements in a graphical user interface.

In addition to pressing a button, other activities to be generated are: entering a character via the keyboard, selecting an item in a list, clicking the mouse.

Events may also occur that are not directly caused by interactions with a user interfaceFor example, an event may be generated

when a timer expires, a counter exceeds a value, a software or hardware failure occurs, an operation is completed.

Page 15: Io package as Java’s basic I/O system continue’d

Event Listeners

A listener is an object that is notified when an event occurs

It has two major requirements:It must have been registered with one or more

sources to receive notifications about specific types of events

It must implement methods to receive and process these notifications.

Page 16: Io package as Java’s basic I/O system continue’d

Event Classes The classes that represent events are core of Java’s event

handling mechanism. The root of java event class hierarchy is EventObject, which

is in java.util. EventObject is the superclass for all events.

Its one constructor is:

EventObject (Object src) src is the object that generates this event. EventObject contains two methods: getSource(): returns the source of the event toString(): returns the string equivalent of the event.

The class AWTEvent defined within the java.awt package is: a superclass of all AWT events that are handled by the delegation

event model. a subclass of EventObject

Page 17: Io package as Java’s basic I/O system continue’d

How to Implement an Event HandlerEvery event handler requires three bits of code:

In the declaration for the event handler class, code that specifies that the class either implements a listener interface or extends a class that implements a listener interface.

public class MyClass implements ActionListener {

Code that registers an instance of the event handler class as a listener upon one or more components

aComponent.addActionListener(instanceOfMyclass)

Code that implements the methods in the listener interface. For example:

public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }

Page 18: Io package as Java’s basic I/O system continue’d
Page 19: Io package as Java’s basic I/O system continue’d

Handling Action Events Action events are fired by subclasses of

AbstractButton and includes buttons, checkboxes, and menus.

AbstractButton button = new JButton ("OK");

button.addActionListener(new MyActionListener()); public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent evt) { // Determine which abstract button fired the event. AbstractButton button = (AbstractButton)evt.getSource(); } }

Page 20: Io package as Java’s basic I/O system continue’d
Page 21: Io package as Java’s basic I/O system continue’d

import java.applet.*;import java.awt.*;import java.awt.event.*;import java.net.*;

public class URLApplet extends Applet implements ActionListener { private TextField URLText = null ; private Button URLButton = null; public URLApplet() { } public void init() { add(new Label ("URL")); URLText = new TextField (30); add (URLText); URLButton = new Button ("Go"); add (URLButton); URLButton.addActionListener(this); }

Page 22: Io package as Java’s basic I/O system continue’d

public void actionPerformed (ActionEvent e) { String actionCommand = e.getActionCommand(); if (e.getSource() instanceof Button) if (actionCommand.equals ("Go")) { System.out.println ("Go"); try { AppletContext context = getAppletContext(); URL url = new URL(URLText.getText()); context.showDocument(url); } catch(Exception ex) { showStatus ("Error "+ex); } } }}