| Applet |
|
| Introduction |
|
| An applet is a small program that is intended not to be run on its own, but rather to be embedded inside or launched from within another application. The most common use of applets are the small programs launched from Web pages. |
|
| Applets are graphical and event driven but, for security reasons, may never access the file system of the platform on which they are run. |
|
|
|
|
|
|
|
|
|
| Applet |
|
| How Applets and Applications Are Different |
|
| Java applications are standalone Java programs that can be run by using just the Java interpreter, for example, from a command line. |
|
| Java applets are run from inside a World Wide Web browser. |
|
| A reference to an applet is embedded in a Web page using a special HTML tag. When a reader, using a Java-enabled browser, loads a Web page with an applet in it, the browser downloads that applet from a Web server and executes it on the local system (the one the browser is running on). |
|
| (The Java interpreter is built into the browser and runs the compiled Java class file from there.) |
|
| Because Java applets run inside a Java browser, they have access to the structure the browser provides: an existing window, an event-handling and graphics context, and the surrounding user interface. |
|
| A single Java program can be written to operate as both a Java application and a Java applet. While we use different procedures and rules to create applets and applications, none of those procedures or rules conflict with each other. |
|
| The features specific to applets are ignored when the program runs as an application, and vice versa. |
|
|
|
|
|
|
| Applet |
|
| Limitation of Applet |
|
| The restrictions on applets include the following: |
| • Applets can't read or write to the reader's file system, which means they cannot delete files or test to see what programs you have installed on the hard drive. |
|
| • Applets can't communicate with any network server other than the one that had originally stored the applet, to prevent the applet from attacking another system from the reader's system. |
|
| • Applets can't run any programs on the reader's system. For UNIX systems, this includes forking a process. |
|
| • Applets can't load programs native to the local platform, including shared libraries such as DLLs. |
|
|
|
|
|
| Applet |
|
| The Applet class |
|
| • Is part of the java.applet package |
| • Is an extension of the Panel class |
|
|
|
|
| • Must be the superclass of any applet that is to be embedded in a Web page or viewed by a Java applet viewer. The Applet class provides a standard interface between applets and their environment. |
| • Is subclassed to define an applet. |
|
| For example, |
| public class MyApplet extends Applet |
| begins the definition of a class named MyApplet that inherits all the features of the Object, Component, Container, Panel, and Applet classes. All that remains is to supply custom features that define application processing. |
|
| • Has many methods. The most frequently used are: |
|
|
|
|
| Other methods exist for retrieving image files, retrieving and playing audio clips, and more. |
|
|
|
|
|
|
| Applet |
|
| Major Applet Activities |
|
| Applets have many different activities that correspond to various major events in the life cycle of the applet-for example, |
| 1. initialization, |
| 2. painting, |
| 3. and mouse events. |
|
| Each activity has a corresponding method, so when an event occurs, the browser or other Java-enabled tool calls those specific methods. |
|
| There are five of the most important methods in an applet's execution: |
| 1. initialization, |
| 2. starting, |
| 3. stopping, |
| 4. destroying, |
| 5. and painting. |
|
|
| Initialization |
| Initialization occurs when the applet is first loaded (or reloaded), similarly to the main() method in applications. The initialization of an applet might include reading and parsing any parameters to the applet, creating any helper objects it needs, setting up an initial state, or loading images or fonts. |
|
| To provide behavior for the initialization of our applet, override the init() method in our applet class: |
public void init()
{
...
} Starting |
|
| After an applet is initialized, it is started. Starting is different from initialization because it can happen many different times during an applet's lifetime, whereas initialization happens only once. Starting can also occur if the applet was previously stopped. |
|
| For example, |
| An applet is stopped if the reader follows a link to a different page, and it is started again when the reader returns to this page. |
| To provide startup behavior for your applet, override the start() method: |
public void start()
{
...
} Stopping |
|
|
| Stopping |
| Stopping occurs when the reader leaves the page that contains a currently running applet, or you can stop the applet yourself by calling stop(). By default, when the reader leaves a page, any threads the applet had s tarted will continue running. |
|
| By overriding stop(), you can suspend execution of these threads and then restart them if the applet is viewed again: |
public void stop()
{
...
} |
|
|
| Destroying |
| Destroying enables the applet to clean up after itself just before it is freed or the browser exits-for example, to stop and remove any running threads, close any open network connections, or release any other running objects. Generally, we won't want to override destroy() unless we have specific resources that need to be released-for example, threads that the applet has created. |
|
| To provide clean-up behavior for your applet, override the destroy() method: |
public void destroy()
{
...
} |
|
|
| Painting |
| Painting is how an applet actually draws something on the screen, be it text, a line, a colored background, or an image. Painting can occur many thousands of times during an applet's life . We override the paint() method if your applet needs to have an actual appearance on the screen (that is, most of the time). |
|
| The paint() method looks like this: |
public void paint(Graphics g)
{
...
} |
|
| paint() takes an argument, an instance of the class Graphics. This object is created and passed to paint by the browser, |
|
|
| import java.awt.Graphics; |
A Simple Applet
The Hello Again applet
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
public class Aman extends java.applet.Applet
{
Font f = new Font("TimesRoman", Font.BOLD, 36);
public void paint(Graphics g)
{
g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello again!", 5, 40);
}
} |
|
|
|
|
| This applet implements the paint() method, one of the major methods described in the previous section (actually, it overrides the default implementation of paint(), which does nothing). Because the applet doesn't actually do much (all it does is print a couple words to the screen), and there's not really anything to initialize, you don't need a start(), stop(), init(), or destroy() method. |
|
|
|
|
|
| Applet |
|
| The life cycle of a Web page applet |
|
| The processing of all Web page applets is as follows: |
| 1. The applet's init() method is automatically called when the page containing the applet is loaded by the browser or applet viewer. Its purpose is to perform applet initialization and it is called only once during the life of the applet. For a simple applet, this is the only required method. An applet does not need a main() method. If one exists, it is ignored. |
|
| 2. The applet's start() method is automatically called after init() and every time the page is revisited. Its purpose is to resume suspended applet processing when the user returns to the page after surfing. |
|
| 3. The applet's stop() method is automatically called when the user surfs to another page or when the browser is being shut down. Its purpose is to suspend applet processing. |
|
| 4. The applet's destroy() method is automatically called after stop() when the browser or applet viewer is being shut down. Its purpose is to release all applet resources and it is called only once during the life of the applet. |
|
|
| A sample applet |
| The following statements define a small applet that displays a message when the user clicks a button. The button may then be re-clicked to clear the message: |
|
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Aman extends Applet implements ActionListener
{
Button b = new Button("Show message");
TextField message = new TextField("", 15);
public void init()
{
resize(300, 100);
setBackground(Color.lightGray);
b.addActionListener(this);
add(b);
message.setFont(new Font("Serif", Font.ITALIC, 24));
message.setForeground(Color.red);
message.setEditable(false);
add(message);
}
public void actionPerformed(ActionEvent e)
{
if (message.getText().length() == 0)
{
message.setText("Hello world!");
b.setLabel("Clear message");
}
else {
message.setText("");
b.setLabel("Show message");
}
}
} |
|
| Notes: |
| 1. By importing the java.applet package, accessing the Applet class is made easier |
|
| 2. The applet needs no WindowListener interface because it isn't a window |
|
| 3. Processing begins with the init() method. It immediately resizes the window to override any size specified by the applet's HTML tag .Everything else about the applet is virtually the same as we would see in an equivalent windows program (with the exception of window event handling which isn't needed). |
|
| 4. NOTE: The procedure for compiling a Java applet is identical to the procedure for compiling a Java program. To test the applet's bytecode, however,we must launch the applet viewer program. This is done by entering the command: appletviewer App.php |
|
|
|
|
|
|
| Applet |
|
| Including an Applet on a Web Page |
|
| After we create a class or classes that contain our applet and compile them into class files as we would any other Java program, we have to create a Web page that will hold that applet by using the HTML language. |
|
| There is a special HTML tag for including applets in Web pages; Java-enabled browsers use the information contained in that tag to locate the compiled class files and execute the applet itself. |
|
|
| The <APPLET> Tag |
| To include an applet on a Web page, use the <APPLET> tag. <APPLET> is a special extension to HTML for including applets in Web pages. |
|
| A simple HTML page. |
<HTML>
<HEAD>
<TITLE>This page has an applet on it</TITLE>
</HEAD>
<BODY>
<P>My second Java applet says:
<BR><APPLET CODE="HelloAgainApplet.class" WIDTH=200 HEIGHT=50>
Hello Again!
</APPLET>
</BODY>
</HTML> |
|
| 1. The CODE attribute indicates the name of the class file that contains this applet, including the .class extension. In this case, the class file must be in the same directory as this HTML file. To indicate applets are in a specific directory, use CODEBASE, described later today. |
|
| 2. WIDTH and HEIGHT are required and are used to indicate the bounding box of the applet-that is, how big a box to draw for the applet on the Web page. Be sure we set WIDTH and HEIGHT to be an appropriate size for the applet; depending on the browser, if our applet draws outside the boundaries of the space you've given it, we may not be able to see or get to those parts of the applet outside the bounding box. |
|
| 3. The text between the <APPLET> and </APPLET> tags is displayed by browsers that do not understand the <APPLET> tag (which includes most browsers that are not Java aware). Because our page may be viewed in many different kinds of browsers, it is a very good idea to include some sort of alternate text or HTML tags here so that readers of your page who don't have Java will see something other than a blank line. |
|
| 4. Note that the <APPLET> tag, like the <IMG> tag itself, is not a paragraph, so it should be enclosed inside a more general text tag, such as <P> or one of the heading tags (<H1>, <H2>, and so on). |
|
|
|
|
|
|
| Applet |
|
| Essential HTML to launch an applet and pass it parameters |
|
| Web pages |
| • Are really text documents, in spite of their fancy features |
| • Can be created or viewed with any text editor, such as Microsoft Word or Windows Notepad |
| • Have a file extension of either .php or .php |
|
|
| HyperText Markup Language (HTML) |
| • Enhances the capabilities of text-only documents to permit special text formatting, links to other pages, and the insertion of objects (audio files, graphic files, etc.). It also provides for the insertion and execution of Java applets. |
|
| • Uses special tags (codes) within the text file. The tags are acted upon by the browser when the Web page is loaded. |
|
| Example: |
| Displaying text in bold |
| This will be bold |
|
| Notes: |
| 1. The tag marks the beginning of bold text and the marks the end of bold text |
| 2. HTML tags are not case sensitive. These tags could have been coded and. |
| 3. Most text formatting tags are paired. There is a beginning tag and ending tag. |
| 4. Other HTML tags exist to specify text size, italicizing, centering, the start of a new paragraph, etc. |
|
| Example: |
| Inserting a graphic image |
| <<IMG SRC=myPhoto.jpg WIDTH=100 HEIGHT=150>> |
|
| Notes: |
| 1. This tag has attributes (parameters) that specify the file name as well as the image width and height in pixels |
| 2. Unlike HTML tags and attributes, file names are case sensitive. Proper capitalization must be maintained. |
| 3. The image will appear at the location of the tag within the document |
| 4. Tags that insert image objects and audio clips are not paired |
|
|
| • Is simplified by the use of various software products. In fact, a detailed understanding of HTML is no longer required to create sophisticated Web pages. |
|
|
| The only HTML you are required to learn in this course involves launching a Java applet. While some packages help generate the tags, it is sometimes necessary to code or edit the tags manually. |
|
|
|
|
|
| Applet |
|
| Launching an applet in an HTML document |
|
| • Requires a pair of tags. The first tag must have attributes that identify the class name of the applet and its size in pixels. The second tag marks the end of the pair. |
| Example: |
| Launching a simple applet |
|
| Notes: |
| 1. In order to launch the applet, the browser must be Java enabled. Otherwise, the tags are ignored. |
|
| 2. The attributes can be coded in any order |
|
| 3. The CODE= attribute specifies the name of the applet's .class file (the bytecode file generated by the Java compiler). If no path is specified, the file is assumed to exist in the same server directory as the web page. This attribute may optionally be coded within quotes. For example, CODE="MyApplet.class" |
|
| 4. The initial pixel width and height of the screen area used by the applet are specified by the WIDTH= and HEIGHT= attributes. A call to the resize() method within the applet class can modify this size. A maximum size of 600 x 400 is recommended for proper display regardless of the graphics resolution. |
|
| 5. There are many other attributes for an applet. |
|
| Notes: |
| 1. The tag is required for each parameter that is passed to an applet. |
|
| 2. The NAME= attribute specifies the case-sensitive identifier of the parameter. The VALUE= attribute specifies a case-sensitive string value associated with the parameter. It must be coded in quotes if it contains any spaces. For example, a tag to pass a message to an applet might contain the attribute VALUE="Hello world!" |
|
| 3. To retrieve the parameter's value from the browser, the following expression must be coded within the applet: |
| getParameter("taxRate") |
|
| In this example, the value received from the browser would be a String object having the value ".06" |
|
| 4. There is no restriction on the number of parameters. Simply code a PARAM tag for each one and place them between the and tags. |
|
|
|
|
|
|
| Applet |
|
| A sample applet that receives a parameter |
|
| This applet is a very slightly modified version of the applet from the previous lesson. The message it displays when the user clicks the button is received as a parameter from the HTML within the Web page. |
|
| To test the applet, a tag such as <applet> must exist in the App.php source file between the ...> and tags. To verify that the tag exists, or to add it if it doesn't, use any text editor (such as Notepad ). |
|
| The applet's code is as follows: |
|
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class App extends Applet implements ActionListener
{
Button b = new Button("Show message");
TextField message = new TextField("", 15);
public void init()
{
resize(300, 100);
setBackground(Color.lightGray);
b.addActionListener(this);
add(b);
message.setFont(new Font("Serif", Font.ITALIC, 24));
message.setForeground(Color.red);
message.setEditable(false);
add(message);
}
public void actionPerformed(ActionEvent e)
{
if (message.getText().length() == 0)
{
message.setText(getParameter("message"));
b.setLabel("Clear message");
}
else
{
message.setText("");
b.setLabel("Show message");
}
}
} |
|
|
|
|
|
|
| Applet |
|
| Posting a Web page that launches a custom applet |
|
| All we must do is upload the .php file of the Web page and the .class file of the applet to your Web server. The rest is automatic! |
|
|
|
|
|
|
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| Introduction |
|
| Nearly all programs require the ability to transfer data in and out of memory. |
| For example, data may be stored on disk or sent over a network. |
|
| The package java.io, part of the standard Java class library, provides a large number of classes designed for handling input and output to files, network connections, and other sources. These I/O classes are known as streams, and provide functionality for reading and writing data in various ways. |
|
| Java's input and output classes: |
| • Input streams-and how to create, use, and detect the end of them-and filtered input streams, which can be nested to great effect. |
|
| • Output streams, which are mostly analogous to (but the inverse of) input streams. |
|
|
|
|
| Managing Input/Output Files in Java |
|
| Streams |
|
| A stream is a path of communication between the source of some information and its destination. This information can come from a file, the computer's memory, or even from the Internet. |
|
| A stream is a path of communication between a source of information and its destination. |
| For example, |
| An input stream allows us to read data from a source, and an output stream allows us to write data to a destination. |
|
|
| The java.io Package |
| To import each individual class or to import the entire java.io package, like this: |
import java.io.InputStream;
import java.io.FilteredInputStream;
import java.io.FileOutputStream;
import java.io.*; |
|
|
| The foundations of this stream framework in the Java class hierarchy are the two abstract classes, InputStream and OutputStream. |
| Inheriting from these classes is a virtual cornucopia of categorized subclasses, demonstrating the wide range of streams in the system, but also demonstrating an extremely well-designed hierarchy of relationships between these streams-one well worth learning from. |
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| Input Streams |
|
| Input streams are streams that allow us to read data from a source. These include the root abstract class InputStream, filtered streams, buffered streams, and streams that read from files, strings, and byte arrays. |
|
|
|
|
|
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| The Abstract Class InputStream |
|
| InputStream is an abstract class that defines the fundamental ways in which a destination (consumer) reads a stream of bytes from some source. |
| read() |
|
| The most important method to the consumer of an input stream is the one that reads bytes from the source. |
|
| Here's the first form of read(): |
InputStream s = getAnInputStreamFromSomewhere();
byte[] buffer = new byte[1024]; // any size will do
if (s.read(buffer) != buffer.length)
System.out.println("I got less than I expected."); |
|
| This form of read() attempts to fill the entire buffer given. If it cannot (usually due to reaching the end of the input stream), it returns the actual number of bytes that were read into the buffer. After that, any further calls to read() return -1, indicating that you are at the end of the stream. Note that the if statement still works even in this case, because -1 != 1024 (this corresponds to an input stream with no bytes in it at all). |
| skip() |
|
| What if you want to skip over some of the bytes in a stream, or start reading a stream from other than its beginning? A method similar to read() does the trick: |
if (s.skip(1024) != 1024)
System.out.println("I skipped less than I expected."); |
|
| This example skips over the next 1024 bytes in the input stream. However, the implementation of skip() in InputStream may skip fewer bytes than the given argument, and so it returns a long integer representing the number of bytes it actually skipped. In this example, therefore, a message is printed if the actual number of bytes skipped is less than 1024. |
| available() |
|
| If for some reason we would like to know how many bytes are in the stream right now, we can ask the following: |
if (s.available() < 1024)
System.out.println("Too little is available right now."); |
|
| This tells us the number of bytes that we can read without blocking. |
mark() and reset()
InputStream s = getAnInputStreamFromSomewhere();
if (s.markSupported()) { // does s support the notion?
. . . // read the stream for a while
s.mark(1024);
. . . // read less than 1024 more bytes
s.reset();
. . . // we can now re-read those bytes
} else {
. . . // no, perform some alternative
} |
|
| When marking a stream, we specify the maximum number of bytes you intend to allow to pass before resetting it. This allows the stream to limit the size of its byte "memory." If this number of bytes goes by and you have not yet used reset(), the mark becomes invalid, and attempting to use reset() will throw an exception. |
|
|
|
| Marking and resetting a stream is most valuable when you are attempting to identify the type of the stream (or the next part of the stream), but to do so, you must consume a significant piece of it in the process. Often, this is because you have several black-box parsers that you can hand the stream to, but they will consume some (unknown to you) number of bytes before making up their mind about whether the stream is of their type. Set a large size for the limit in mark(), and let each parser run until it either throws an error or completes a successful parse. If an error is thrown, use reset() and try the next parser. |
|
close()
InputStream s = alwaysMakesANewInputStream();
try {
. . . // use s to your heart's content
} finally {
s.close(); } |
|
| Get used to this idiom (using finally); it's a useful way to be sure something (such as closing the stream) always gets done. |
|
| Java provides many classes that make "I/O" (input and output) relatively easy and platform independent. In this lesson, we will learn how to act upon the file structure of a platform from inside a Java application. Note that Java applets are NOT permitted to access a platform's file structure for security reasons. |
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| The File class |
|
| • Is part of the java.io package. You will need an import statement to access the class with its abbreviated name. |
|
| • Is an extension of the Object class |
|
|
|
|
| • Encapsulates platform-independent information about a file or a directory. |
|
| While all platforms use pathname strings to name files and directories, they do not agree on the format of these strings. For example, the Windows pathname string is not the same as the Unix pathname string. |
|
| Regardless of platform, however, all pathnames have two components: |
| 1. An optional system-dependent prefix string (such as the disk-drive specifier followed by "/" for the Unix root directory or "" for the Windows root directory) |
|
| 2. A sequence of zero or more string names where each name, except for the last, denotes a directory. The the last name may denote either a directory or a file. A system-dependent separator ("/" for Unix or "" for Windows) is used between each name. |
|
| For example, |
| The following represents a valid Windows pathname: |
| C:My DocumentsNew CoursesLesson55.php |
|
| Regardless of the platform, the File class presents a system-independent view of pathnames. |
|
|
| • Has a number of static fields. These two are the most useful: |
|
|
|
|
|
| For example, |
| The following program can determine if it is running under Windows: |
import java.io.*;
public class AppFile
{
public static void main(String[] args)
{
if (File.separator.equals(""))
System.out.println("Windows");
else
System.out.println("Not Windows");
}
} |
|
|
|
| • Has several constructors. The most frequently used constructs a File object from a pathname string as shown by the following statement: |
| File f = new File("C:My DocumentsMiscResume.doc"); |
|
| NOTE: |
| Constructing a File object does NOT create a disk file. It only constructs a platform-independent object for referencing the file. |
|
|
| • Has a number of methods, some of which WILL create, rename, and delete a disk file or a directory. They should obviously be used with caution. The most frequently used methods are: |
|
|
|
| Consult the Java API documentation for more details. |
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| The FileDialog class |
|
| • Is part of the java.awt package. You will need an import statement to access the class with its abbreviated name. |
|
| • Has many ancestor classes as indicated by the following diagram: |
|
|
|
|
|
| • Can be instantiated to display a modal dialog window from which the user can select a file. Because it is a modal dialog, once an application makes a FileDialog object visible, it cannot continue until the user has chosen a file. |
|
| • Has two static fields that indicate whether the file will be used for input or output. |
| They are |
|
|
|
|
|
| • Has several constructors. The most frequently used is demonstrated by |
FileDialog fd = new FileDialog(this, "Choose file", FileDialog.LOAD);
fd.setVisible(true); |
|
| which constructs and displays a file dialog window for the current (this) object. The title of the file dialog window will be "Choose file", and the chosen file will be used for input. |
|
|
| • Has a number of methods. The most frequently used are as follows: |
|
|
|
| Consult the Java API documentation for more details. |
|
|
| Sample program |
| The following menu-driven, Windows program uses the File and FileDialog classes to display a variety of information about a file selected by the user: |
|
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class App extends Frame implements ActionListener
{
// Object references.
MenuBar mainBar;
Menu fileMenu;
MenuItem find;
MenuItem exit;
TextArea fileInfo;
// Processing starts here.
public static void main(String[] args)
{
App myWindow = new App("File Analyzer");
myWindow.setSize(500, 200);
myWindow.setVisible(true);
}
// Class constructor.
public App(String title)
{
// Usual boilerplate for startup and shutdown.
super(title);
//addWindowListener();
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0);
}
}
);
// Create the frame's menu bar.
mainBar = new MenuBar();
setMenuBar(mainBar);
fileMenu = new Menu("File");
find = new MenuItem("Find");
find.addActionListener(this);
fileMenu.add(find);
fileMenu.addSeparator();
exit = new MenuItem("Exit");
exit.addActionListener(this);
fileMenu.add(exit);
mainBar.add(fileMenu);
// Create the file information text area.
fileInfo = new TextArea(" Use the menu bar to find a file...",
10, 40, TextArea.SCROLLBARS_NONE);
fileInfo.setFont(new Font("Monospaced", Font.PLAIN, 12));
fileInfo.setEditable(false);
add(fileInfo);
}
// Required method of the ActionListener interface.
public void actionPerformed(ActionEvent e)
{
// If the user selected "File" | "Find" from the menu, let them
// choose a file to be analyzed. Then, display its information.
if (e.getSource().equals(find))
{
// Create and display a modal file dialog box through which the
// user can choose the file they want to analyze.
FileDialog fd = new FileDialog(this, "Choose file", FileDialog.LOAD);
fd.setVisible(true);
// Construct a File object for the file the user selected.
File f = new File(fd.getDirectory() + File.separator + fd.getFile());
// Display information about the file the user selected.
fileInfo.setText(" FILE INFORMATION ");
fileInfo.append(" Path: " + f.getPath());
fileInfo.append(" Directory: " + fd.getDirectory());
fileInfo.append(" File: " + f.getName());
fileInfo.append(" Last modified: " +
new Date(f.lastModified()).toString());
fileInfo.append(" Byte length: " + f.length());
fileInfo.setCaretPosition(0);
}
// If the user selected "File" | "Exit" from the menu, terminate
// the application.
if (e.getSource().equals(exit)) {
dispose();
System.exit(0);
}
}
} |
|
|
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| Low-level and high-level stream classes |
|
| At its lowest level, all Java I/O involves a stream of bytes either entering or leaving memory as shown by this diagram: |
|
|
|
|
| Obviously, sending and receiving individual bytes would be tedious and difficult for an application to manage. For that reason, several packaged classes exist that make it easy for a program to read and write larger units of data. |
|
| Most programs use a "high-level" stream class object that is "chained" (connected) to a "low-level" stream class object. While the low-level stream class object handles byte I/O, the high-level stream class object will allow the program to read and write primitive data values and even objects (as shown below). |
|
|
|
|
|
| There are many stream classes, but you will only be required to know the ones that are highlighted below: |
|
|
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| The FileOutputStream class |
|
| • Is part of the java.io package |
|
| • Is an extension of the OutputStream class, an abstract class that describes the behavior of an output stream |
|
|
|
|
| • Is a low-level class that can be used to send individual, 8-bit bytes to a stream |
|
| • Has several constructors. The most frequently used constructs a FileOutputStream object from a File object that encapsulates the file's pathname. For example, if fd is the reference of a File object |
|
|
| FileOutputStream out = new FileOutputStream(fd); |
| It will construct a FileOutputStream object for sending bytes to the file. If the file already exists, its contents will be replaced (there is an overloaded constructor to specify appending). Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch. |
|
| • Has a few useful methods. The two most used are: |
|
|
|
|
| Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details. |
|
|
| • Example. The following program can be used to create a file of numbers on disk. |
| // Open an output stream for the file. |
| out = new FileOutputStream(fd); |
|
| // This loop asks the user to enter a import |
|
java.io.*;
public class AppFOS
{
public static void main(String[] args)
{
// Local variables and object references.
char again = 'y';
File fd;
FileOutputStream out;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to write data to the output stream.
try
{
//number and writes it to the
// stream. The user is then asked if they want to enter another.
while (again == 'Y' || again == 'y')
{
System.out.print("Enter a number: ");
int theNumber = Keyboard.readInt();
out.write(theNumber);
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
}
// Close the stream.
out.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
} |
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| The FileInputStream class |
|
| • Is part of the java.io package |
|
| • Is an extension of the InputStream class, an abstract class that describes the behavior of an input stream |
|
|
|
|
| • Is a low-level class that can be used to read individual, 8-bit bytes from a stream |
|
| • Has several constructors. The most frequently used constructs a FileInputStream object from a File object that encapsulates the file's pathname. For example, if fd is the reference of a File object |
| FileInputStream in = new FileInputStream(fd); |
|
| It will construct a FileInputStream object for reading bytes from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch. |
|
| • it has a few useful methods. The most used are: |
|
|
|
|
| Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details. |
|
| • Example. The following program can be used to read byte values from a disk file. It can be used to display the values stored by the previous sample program. |
|
import java.io.*;
public class AppFIS
{
public static void main(String[] args)
{
// Local variables and object references.
File fd;
FileInputStream in;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to read data from the input stream.
try
{
// Open an input stream for the file.
in = new FileInputStream(fd);
// This loop reads a byte from the stream and displays
// its value. The loop ends when no more bytes are available.
while (in.available() > 0)
{
System.out.println(in.read());
}
// Close the stream.
in.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
} |
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| The DataOutputStream class |
|
| • Is part of the java.io package |
|
| • Is an extension of the FilterOutputStream class (a superclass that facilitates the chaining of high-level and low-level output streams) |
|
|
|
|
| • Is a high-level class that can be used to send primitive values and UTF ("Unicode Transformation Format") strings to a stream |
|
| • Has a single constructor that "chains" to an object that descends from the OutputStream class (such as a FileOutputStream object). For example, if fd is the reference of a File object |
| DataOutputStream out = new DataOutputStream(new FileOutputStream(fd)); |
|
| It will construct a DataOutputStream object chained to a FileOutputStream object for sending primitive values and UTF strings to the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch. |
|
| • Has many useful methods as follows: |
|
|
|
|
| Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details. |
|
| • Example. The following program can be used to create a file of double values on disk. |
|
import java.io.*;
public class App
{
public static void main(String[] args)
{
// Local variables and object references.
char again = 'y';
File fd;
DataOutputStream out;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to write data to the output stream.
try
{
// Open an output stream for the file.
out = new DataOutputStream(new FileOutputStream(fd));
// This loop asks the user to enter a number and writes it to the
// stream. The user is then asked if they want to enter another.
while (again == 'Y' || again == 'y') {
System.out.print("Enter any real number (n.n): ");
double theNumber = Keyboard.readDouble();
out.writeDouble(theNumber);
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
}
// Close the stream.
out.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
} |
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| The DataInputStream class |
|
| • Is part of the java.io package |
|
| • Is an extension of the FilterInputStream class (a superclass that facilitates the chaining of high-level and low-level input streams) |
|
| • Is a high-level class that can be used to read primitive values and UTF ("Unicode Transformation Format") strings from a stream |
|
| • Has a single constructor that "chains" to an object that descends from the InputStream class (such as a FileInputStream object). For example, if fd is the reference of a File object |
| DataInputStream in = new DataInputStream(new FileInputStream(fd)); |
|
| It will construct a DataInputStream object chained to a FileInputStream object for reading primitive values and UTF strings from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch. |
|
| • Has many useful methods as follows: |
|
|
|
|
| Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details. |
|
| • Example. The following program can be used to read a file of double values from disk. It can be used to display the values stored by the previous sample program. |
|
import java.io.*;
public class App
{
public static void main(String[] args)
{
// Local variables and object references.
File fd;
DataInputStream in;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to read data from the input stream.
try {
// Open an input stream for the file.
in = new DataInputStream(new FileInputStream(fd));
// This loop reads a double value from the stream and displays
// it. The loop ends when end of file is reached.
try
{
while (true)
{
System.out.println(in.readDouble());
}
}
catch (EOFException e)
{
System.out.println("");
}
// Close the stream.
in.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
} |
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| The ObjectOutputStream class |
|
| • Is part of the java.io package |
|
| • Is an extension of the OutputStream class, an abstract class that describes the behavior of an output stream |
|
|
|
|
| • Is a high-level class that can be used to send primitive values and "serializable" objects to a stream. All that is needed for an object to be serializable, is that its class must implement the Serializable interface. For example, if a Customer class is to be serializable, its header may be coded |
| public class Customer implements Serializable |
|
| The interface requires no methods. |
| Many packaged classes are serializable including all wrapper classes, String and Stringbuffer classes, Vector and Array classes, and the collection classes. In other words, an entire collection, such as a SortedMap, can be stored as an object on disk! |
|
| • Has overloaded constructors but the most useful "chains" to an object that descends from the OutputStream class (such as a FileOutputStream object). For example, if fd is the reference of a File object |
| ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fd)); |
|
| It will construct a ObjectOutputStream object chained to a FileOutputStream object for sending primitive values and serializable objects to the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch. |
|
| • Has many useful methods as follows: |
|
|
|
|
| Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details. |
|
| • Example. The following program can be used to create a file of multiple array objects on disk. |
|
import java.io.*;
public class App
{
public static void main(String[] args)
{
// Local variables and object references.
char again = 'y';
String[] array;
File fd;
ObjectOutputStream out;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to write data to the output stream.
try
{
// Open an output stream for the file.
out = new ObjectOutputStream(new FileOutputStream(fd));
// This loop constructs an array with values entered by the user
// and writes the array to the file. The user is given the option
// of repeating the loop to construct and store another array.
while (again == 'Y' || again == 'y')
{
System.out.print("How many strings will you enter? ");
array = new String[Keyboard.readInt()];
for (int i = 0; i < array.length; i++) {
System.out.print("Enter a string: ");
array[i] = Keyboard.readString();
}
out.writeObject(array);
System.out.print("Again? (Y/N) ");
again = Keyboard.readChar();
}
// Close the stream.
out.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e) {
System.out.println(e.getMessage());
}
}
} |
|
|
|
|
|
|
| Managing Input/Output Files in Java |
|
| The ObjectInputStream class |
|
| • Is part of the java.io package |
|
| • Is an extension of the InputStream class, an abstract class that describes the behavior of an input stream |
|
|
|
|
| • Is a high-level class that can be used to read primitive values and serializable objects from a stream |
|
| • Has overloaded constructors but the most useful "chains" to an object that descends from the InputStream class (such as a FileInputStream object). For example, if fd is the reference of a File object |
| ObjectInputStream out = new ObjectInputStream(new FileInputStream(fd)); |
|
| will construct a ObjectInputStream object chained to a FileInputStream object for reading primitive values and serializable objects from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch. |
|
| • Has many useful methods as follows: |
|
|
|
|
| Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details. |
|
|
| • Example. The following program can be used to read a file of array objects from disk. It can be used to display the array values stored by the previous sample program. |
|
import java.io.*;
public class App
{
public static void main(String[] args)
{
// Local variables and object references.
File fd;
ObjectInputStream in;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to read data from the input stream.
try
{
// Open an input stream for the file.
in = new ObjectInputStream(new FileInputStream(fd));
// This loop reads a array objects from the stream and displays
// their contents. The loop ends when end of file is reached.
try
{
while (true)
{
String[] array = (String[]) in.readObject();
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
System.out.println("<< END OF ARRAY >>");
}
}
catch (EOFException e) {
System.out.println("<< END OF FILE >>");
}
// Close the stream.
in.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e) {
System.out.println(e.getMessage());
}
// Catch an ClassNotFoundException if one is thrown.
catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
0 comments: