io package as Java’s basic I/O system

Download Report

Transcript io package as Java’s basic I/O system

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);
}
}
//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]);
} } }
HERE IS A SAMPLE RUN
C:\JBUILDER8\JDK1.4\bin\javawclasspath"C:\WINDOWS\jbproject\untitled40\classes;C:\...........JBUILDER
8\JDK1.4\JRE\classes;C:\JBUILDER8\jdk1.4\lib\tools.jar"
untitled40.Editor
Enter lines of text.
Enter ‘Stop’ to quit.
13
20
46
-43
-346789
stop
Here is your file:
13
20
46
-43
-346789
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.
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');
}
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 program
 PrintWriter defines several constructors. The one is:
PrintWriter(OutputStream outputStream,
boolean flushOnNewline)
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:
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);
//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”);
The output is:
int i=-7;
untitled42.PrintWriterDemo
This is a string
pw.println(i);
-7
4.5E-7
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.
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.*;
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 event
Once 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.
 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 interface
For 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.
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.
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
How to Implement an Event Handler
Every 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... }
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();
}
}
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);
}
{
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);
}
}
}
}