MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *CAUTIONThe clone() method is a relatively expensive operation to perform in terms of memory utilization and execution time. Because the new Hashtable still refers directly to the objects (keys and values) stored in the old table, caution should be used to avoid making changes that will disrupt the original Hashtable. PRIVATE | MACROBUTTON HtmlDirect | The Hashtable class extends the java.util.Dictionary class and implements the java.lang.Cloneable interface. Table 19.10 summarizes the methods of the Hashtable class. PRIVATE MACROBUTTON HtmlDirect
Table 19.10. The Hashtable interface. PRIVATE MACROBUTTON HtmlDirect PRIVATE MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *ConstructorsHashtable( )Constructs an empty Hashtable.Hashtable(int)Constructs an empty Hashtable with the specified capacity.Hashtable(int, float)Constructs an empty Hashtable given capacity and load factor. PRIVATE MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *Methodsclear( )Deletes all elements from the Hashtable.clone( )Creates a clone of the Hashtable.contains(Object)True if the specified object is an element of the Hashtable.containsKey(Object)True if the Hashtable contains the specified key.elements( )Returns an Enumeration of the Hashtables values.get(Object)Returns the object associated with the specified key.isEmpty( )True if the Hashtable has no elements.keys( )Returns an Enumeration of the keys.put(Object, Object)Stores the specified key and value pair in the Hashtable.rehash( )Rehashes the contents of the table into a bigger table.remove(Object) Removes an element from the Hashtable by its key.size( )Returns the number of elements stored.toString( )Converts the contents to a very long string.Refer also to hashCode, equals. PRIVATE MACROBUTTON HtmlDirect
Properties
This class is a Hashtable that can be stored and restored from a stream. It is used to implement persistent properties. It also allows for an unlimited level of nesting by searching a default property list if the required property is not found. PRIVATE MACROBUTTON HtmlDirect
The example program Properties1 in Listing 19.10 creates two Properties lists. One will be the default property list and the other will be the user-defined property list. When the user property list is created, the default Properties object is passed. When the user property list is searched, if the key value is not found, the default Properties list will be searched. PRIVATE MACROBUTTON HtmlDirect
Listing 19.10. Properties1.javaProperties example program.
import java.io.DataInputStream;import java.lang.Integer;import java.util.Properties;class Properties1 { public static void main(String args[]) throws java.io.IOException { int numElements=4; String defaultNames[]={Red,Green,Blue,Purple}; int defaultValues[]={1,2,3,4}; String userNames[]={Red,Yellow,Orange,Blue}; int userValues[]={100,200,300,400}; DataInputStream dis=new DataInputStream(System.in); Properties defaultProps=new Properties(); Properties userProps=new Properties(defaultProps); for (int i=0;i MACROBUTTON HtmlDirect
Notice that the getProperties() method is used instead of the inherited get() method. The get() method only searches the current Properties object. The getProperties() method must be used in order to have the default Properties list searched. An alternative form of the getProperties() method has a second argument that is a default Properties list to search instead of the default specified when the Properties object was created. PRIVATE MACROBUTTON HtmlDirect
The propertyNames() method can be used to return an Enumeration that can be used to index through all of the property names. This Enumeration includes the property names from the default Properties list. Likewise, the list() method, which prints the Properties list tothe standard output, will list all of the properties of the current Properties object and thosein the default Properties object. PRIVATE MACROBUTTON HtmlDirect
Properties objects can be written to and read from a stream using the save() and load() methods respectively. In addition to the output or input stream, the save method has an additional string argument that will be written to the beginning of the stream as a header comment. PRIVATE MACROBUTTON HtmlDirect
The Properties class extends the Hashtable class. Table 19.11 summarizes the methods of the Properties class. PRIVATE MACROBUTTON HtmlDirect
Table 19.11. The Properties interface. PRIVATE MACROBUTTON HtmlDirect PRIVATE MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *VariablesdefaultsDefault Properties list to search. PRIVATE MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *ConstructorsProperties( )Constructs an empty property list.Properties(Properties)Constructs an empty property list with specified default. PRIVATE MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *MethodsgetProperty(string)Returns a property given the key.getProperty(string, string) Returns a property given the specified key and default.list(PrintStream)Lists the properties to a stream for debugging.load(InputStream)Reads the properties from an InputStream.. propertyNames( )Returns an Enumeration of all of the keys.save(OutputStream, string)Writes the properties to an OutputStream.Observable
This class acts as a base class for objects that wish to be observed by other objects that implement the Observer interface. An Observable object can notify its Observers whenever theObservable object is modified using the notifyObservers() method. This method accomplishes the notification by invoking the update() method of all of its Observers, optionally passing a data object which is passed to notifyObservers. Observable objects may have any number of Observers. PRIVATE MACROBUTTON HtmlDirect
Table 19.12 summarizes the complete interface of the Observable class. PRIVATE MACROBUTTON HtmlDirect
Table 19.12. Observable interface. PRIVATE MACROBUTTON HtmlDirect PRIVATE MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *ConstructorsObservable( ) PRIVATE MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *MethodsaddObserver(Observer)Adds an Observer to the observer list.clearChanged( )Clears an observable change.countObservers( )Returns the number of Observers.deleteObserver(Observer)Deletes an Observer from the observer list.deleteObservers( )Deletes all Observers from the observer list.hasChanged( ) True if an observable change occurred.notifyObservers( )Notifies all observers if an observable change occurred.notifyObservers(Object)Notifies all observers of a specific observable change.setChanged( )Sets a flag to indicate that an observable change occurred.Refer also to Observer. PRIVATE MACROBUTTON HtmlDirect
Summary
This chapter has described the classes that make up the Java Utilities package. This package provides complete implementations of some of the most useful data types (other than the fundamental numeric types) and the basic data structures needed by programmers. Many of the data types and data structures that you will develop using Java will be based on the classes found in the Utilities package. This chapter should be a good starting point for understanding the utility of these important Java classes and for understanding how to use them effectively. PRIVATE MACROBUTTON HtmlDirect
Chapter 20
The I/O package
It would be impossible for a program to do anything useful without performing some kind of input or output of data. Most programs require input from the user and in return output information to the screen, printer, and often to files. The Java I/O package provides an extensive set of classes for handling input and output to and from many different devices. In this chapter you learn about the primary classes contained in the I/O package, along with some examples that show off the capabilities of these classes. PRIVATE MACROBUTTON HtmlDirect
The I/O package, which is also known as java.io, contains many classes, each with a variety of member variables and methods. This chapter does not take an exhaustive look at every class and method contained in the I/O package. Instead, you may view this chapter as a tutorial on how to perform basic input and output using the more popular I/O classes. Armed with the information learned in this chapter, you will be ready to begin using the Java I/O classes in your own programs. And should you choose to explore the more complex I/O classes supported by Java, you will be prepared for the challenge. PRIVATE MACROBUTTON HtmlDirect
Input Stream Classes
The Java input model is based on the concept of an input stream. An input stream can be thought of much like a physical (and certainly more literal) stream of water flowing from a water plant into the pipes of a water system. The obvious difference is that an input stream deals with binary computer data rather than physical water. The comparison is relevant, however, because the data going into an input stream flows like the water being pumped into a pipe. Data that is pumped into an input stream can be directed in many different ways, much like water is directed through the complex system of pipes that make up a water system. The data in an input stream is transmitted a byte at a time, which is roughly analogous to individual drops of water flowing into a pipe. PRIVATE MACROBUTTON HtmlDirect
More practically speaking, Java uses input streams as the means of reading data from an input source, such as the keyboard. The basic input stream classes supported by Java follow: PRIVATE MACROBUTTON HtmlDirect
InputStream
BufferedInputStream
DataInputStream
FileInputStream
StringBufferInputStream
The InputStream Class
The InputStream class is an abstract class that serves as the base class for all the other input stream classes. InputStream defines a basic interface for reading streamed bytes of information. The methods defined by the InputStream class will become very familiar to you because they serve a similar purpose in every InputStream derived class. This design approach enables you to learn the protocol for managing input streams once, and then apply it to different devices using an InputStream derived class. PRIVATE MACROBUTTON HtmlDirect
The typical scenario when using an input stream is to create an InputStream derived object and tell it you want to input information (by calling an appropriate method). If no input information is currently available, the InputStream uses a technique known as blocking to wait until input data becomes available. An example of when blocking will take place is the case of using an input stream to read information from the keyboard. Until the user has typed in information and pressed Return, there is no input available to the InputStream object. The InputStream object then waits (blocks) until the user presses Return, in which case the input data becomes available and the InputStream object can process it as input. PRIVATE MACROBUTTON HtmlDirect
The InputStream class defines the following methods: PRIVATE MACROBUTTON HtmlDirect
abstract int read()
int read(byte b[])
int read(byte b[], int off, int len)
long skip(long n)
int available()
synchronized void mark(int readlimit)
synchronized void reset()
boolean markSupported()
void close()
InputStream defines three different read methods for reading input data in various ways. The first read method takes no parameters and simply reads a byte of data from the input stream and returns it as an integer. This version of read returns -1 if the end of the input stream is reached. Because this version of read returns a byte of input as an int, you will need to cast it to a char if you are reading characters. The second version of read takes an array of bytes as its only parameter, enabling you to read multiple bytes of data at once. You have to make sure that the byte array passed into read is large enough to hold the information being read, or an IOException will be thrown. This version of read returns the actual number of bytes read, or -1 if the end of the stream is reached. The last version of read takes a byte array, an integer offset, and an integer length as parameters. This version of read is very similar to the second version, except it enables you to specify where in the byte array you want the new information placed. The off parameter specifies the offset into the byte array to start placing new data, and the len parameter specifies the maximum number of bytes to read. PRIVATE MACROBUTTON HtmlDirect
The skip method is used to skip over bytes of data in the input stream. skip takes a long value n as its only parameter, which specifies how many bytes of input to skip. It returns the actual number of bytes skipped, or -1 if the end of the input stream is reached. PRIVATE MACROBUTTON HtmlDirect
The available method is used to determine the number of bytes of input data that can be read without blocking. available takes no parameters and returns the number of available bytes. This method is useful if you want to ensure that there is input data available so as to avoid the blocking mechanism. PRIVATE MACROBUTTON HtmlDirect
The mark method marks the current position in the stream. This position can later be returned to using the reset method. The mark and reset methods are useful in situations where you want to read ahead in the stream but not lose your original position. An example of this situation is verifying a file type, such as an image file. You would probably read the file header first and mark the position at the end of the header. You would then read some of the data to make sure it follows the format expected for that file type. If the data doesnt look right, you can reset the read pointer and try a different technique. PRIVATE MACROBUTTON HtmlDirect
Notice that the mark method takes an integer parameter, readlimit. readlimit specifies how many bytes can be read before the mark becomes invalidated. In effect, readlimit determines how far you can read ahead and still be able to reset the marked position. The markSupported method returns a Boolean value representing whether or not an input stream supports the mark/reset functionality. PRIVATE MACROBUTTON HtmlDirect
Finally, the close method closes an input stream and releases any resources associated with the stream. It is not necessary to explicitly call close, since input streams are automatically closed when the InputStream object is destroyed. Although it is not necessary, calling close immediately after you are finished using a stream is a good programming practice. The reason for this is that close causes the stream buffer to be flushed, which helps avoid file corruption. PRIVATE MACROBUTTON HtmlDirect
The System.in Object
The keyboard is the most standard input device for retrieving user input. The System class contained in the language package contains a member variable that represents the keyboard, or standard input stream. This member variable is called in and is an instance of the InputStream class. This variable is useful for reading user input from the keyboard. Listing 20.1 contains the ReadKeys1 program, which shows how the System.in object can be used along with the first version of the read method. This program can be found on the CD-ROM in the file ReadKeys1.java. PRIVATE MACROBUTTON HtmlDirect PRIVATE MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *NOTEI mentioned the keyboard as being the standard input stream. This isnt totally true, because the standard input stream can receive input from any number of sources. Although the keyboard certainly is the most common method of feeding input to the standard input stream, it is not the only method. An example of the standard input stream being driven by a different input source is the redirection of a file into a stream.Listing 20.1. The ReadKeys1 class.
class ReadKeys1 { public static void main (String args[]) { StringBuffer s = new StringBuffer(); char c; try { while ((c = (char)System.in.read()) != \n) { s.append(c); } } catch (Exception e) { System.out.println(Error: + e.toString()); } System.out.println(s); }}
PRIVATE MACROBUTTON HtmlDirect
The ReadKeys1 class first creates a StringBuffer object called str. It then enters a while loop that repeatedly calls the read method until a newline character is detected (the user hits Return). Notice that the input data returned by read is cast to a char type before being stored in the character variable c. Each time a character is read, it is appended to the string buffer using the append method of StringBuffer. It is important to see how any errors caused by the read method are handled by the try/catch exception handling blocks. The catch block simply prints an error message to the standard output stream based on what error occurred. Finally, when a newline character is read from the input stream, the println method of the standard output stream is called to output the string to the screen. Youll learn more about the standard output stream a little later in this chapter. PRIVATE MACROBUTTON HtmlDirect
Listing 20.2 contains ReadKeys2, which is similar to ReadKeys1 except that it uses the second version of the read method. This read method takes an array of bytes as a parameter to store the input that is read. ReadKeys2 can be found on the CD-ROM in the file ReadKeys2.java. PRIVATE MACROBUTTON HtmlDirect
Listing 20.2. The ReadKeys2 class.
class ReadKeys2 { public static void main (String args[]) { byte buf[] = new byte[80]; try { System.in.read(buf); } catch (Exception e) { System.out.println(Error: + e.toString()); } String s = new String(buf, 0); System.out.println(s); }}
PRIVATE MACROBUTTON HtmlDirect
In ReadKeys2, an array of bytes is created that is 80 bytes long. A single read method call is performed that reads everything the user has typed. The input is blocked until the user presses Return, in which case the input becomes available and the read method fills the byte array with the new data. A String object is then created to hold the constant string previously read. Notice that the creation method, or constructor, used to create the String object takes an array of bytes (buf) as the first parameter and appends the high byte value specified in the second parameter to each byte, thus forming 16-bit Unicode characters. Because the standard ASCII characters map to Unicode characters with zeros in the high byte, passing 0 as the high byte to the constructor works perfectly. Finally, println is again used to output the string. PRIVATE MACROBUTTON HtmlDirect
The ReadKeys3 program in Listing 20.3 shows how to use the last version of the read method. This version of read again takes an array of bytes, as well as an offset and length for determining how to store the input data in the byte array. ReadKeys3 can be found on the CD-ROM in the file ReadKeys3.java. PRIVATE MACROBUTTON HtmlDirect
Listing 20.3. The ReadKeys3 class.
class ReadKeys3 { public static void main (String args[]) { byte buf[] = new byte[10]; try { System.in.read(buf, 0, 10); } catch (Exception e) { System.out.println(Error: + e.toString()); } String s = new String(buf, 0); System.out.println(s); }}
PRIVATE MACROBUTTON HtmlDirect
ReadKeys3 is very similar to ReadKeys2, with one major difference: the third version of the read method is used to limit the maximum number of bytes read into the array. The size of the byte array is also shortened to ten bytes to show how this version of read handles it when more data is available than the array can hold. Remember that this version of read can also be used to read data into a specific offset of the array. In this case, the offset is specified as 0 so that the only difference is the maximum number of bytes that can be read (10). This is a useful technique of guaranteeing that you dont overrun a byte array. PRIVATE MACROBUTTON HtmlDirect
The BufferedInputStream Class
The BufferedInputStream class, as its name implies, provides a buffered stream of input. This means that more data is read into the buffered stream than you might have requested, meaning that subsequent reads come straight out of the buffer, rather than the input device. This can result in much faster read access, because reading from a buffer is really just reading from memory. BufferedInputStream implements all of the same methods defined by InputStream. As a matter of fact, it doesnt implement any new methods of its own. However, the BufferedInputStream class does have two different constructors, which follow: PRIVATE MACROBUTTON HtmlDirect
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)
Notice that both constructors take an InputStream object as the first parameter. The only difference between the two is the size of the internal buffer. In the first constructor, a default buffer size is used, whereas in the second constructor you specify the buffer size with the size integer parameter. To support buffered input, the BufferedInputStream class also defines a handful of member variables, which follow: PRIVATE MACROBUTTON HtmlDirect
byte buf[]
int count
int pos
int markpos
int marklimit
The buf byte array member is the buffer where input data is actually stored. The count member variable keeps up with how many bytes are stored in the buffer. The pos member variable keeps up with the current read position in the buffer. The markpos member variable specifies the current mark position in the buffer as set using the mark method. markpos is equal to -1 if no mark has been set. And finally, the marklimit member variable specifies the maximum number of bytes that can be read before the mark position is no longer valid. marklimit is set by the readlimit parameter passed into the mark method. All these member variables are specified as protected, so you will probably never actually use any of them. However, seeing these variables should give you some insight into how the BufferedInputStream class implements the methods defined by InputStream. PRIVATE MACROBUTTON HtmlDirect
Listing 20.4 contains the ReadKeys4 program, which uses a BufferedInputStream object instead of System.in to read input from the keyboard. ReadKeys4 can be found in the file ReadKeys4.java on the CD-ROM. PRIVATE MACROBUTTON HtmlDirect
Listing 20.4. The ReadKeys4 class.
import java.io.*;class ReadKeys4 { public static void main (String args[]) { BufferedInputStream in = new BufferedInputStream(System.in); byte buf[] = new byte[10]; try { in.read(buf, 0, 10); } catch (Exception e) { System.out.println(Error: + e.toString()); } String s = new String(buf, 0); System.out.println(s); }}
PRIVATE MACROBUTTON HtmlDirect
Notice first that the BufferedInputStream class must be imported from the I/O package. Actually, in this case the * qualifier is used to import all the classes in the I/O package. The BufferedInputStream object is created by passing the System.in InputStream into its constructor. From there on, the program is essentially the same as ReadKeys3, except that the read method is called on the BufferedInputStream object rather than System.in. PRIVATE MACROBUTTON HtmlDirect
The DataInputStream Class
The DataInputStream class is useful for reading primitive Java data types from an input stream in a portable fashion. There is only one constructor for DataInputStream, which simply takes an InputStream object as its only parameter. This constructor is defined as follows: PRIVATE MACROBUTTON HtmlDirect
DataInputStream(InputStream in)
DataInputStream implements the following useful methods beyond those defined by InputStream: PRIVATE MACROBUTTON HtmlDirect
final int skipBytes(int n)
final void readFully(byte b[])
final void readFully(byte b[], int off, int len)
final String readLine()
final boolean readBoolean()
final byte readByte()
final int readUnsignedByte()
final short readShort()
final int readUnsignedShort()
final char readChar()
final int readInt()
final long readLong()
final float readFloat()
final double readDouble()
The skipBytes method works very similarly to skip, with the exception being that skipBytes blocks until all bytes are skipped. The number of bytes to skip is determined by the integer parameter n. There are two readFully methods implemented by DataInputStream. These methods are similar to the read methods, except that they block until all data has been read. The normal read methods only block until some data is available, not all. The readFully methods are to the read methods what skipBytes is to skip. PRIVATE MACROBUTTON HtmlDirect
The readLine method is used to read a line of text that has been terminated with a newline (\n), carriage return (\r), carriage return/newline (\r\n), or end-of-file character sequence (EOF). readLine returns the line of text in a String object. Listing 20.5 contains the ReadFloat program, which uses the readLine method to read a floating point value from the user. PRIVATE MACROBUTTON HtmlDirect
Listing 20.5. The ReadFloat class.
import java.io.*;class ReadFloat { public static void main (String args[]) { DataInputStream in = new DataInputStream(System.in); String s = new String(); try { s = in.readLine(); float f = Float.valueOf(s).floatValue(); System.out.println(f); } catch (Exception e) { System.out.println(Error: + e.toString()); } }}
PRIVATE MACROBUTTON HtmlDirect
In ReadFloat, a DataInputStream object is first created based on System.in. A String object is then created to hold the input line of text. The readLine method is called with the resulting line of text being stored in the String object s. A floating point number is extracted from the string by first getting a Float object from the string by using the valueOf static method of the Float class. The floatValue method is then called on the Float object to get a float value, which is then stored in the float variable f. This value is then output to the screen using println. PRIVATE MACROBUTTON HtmlDirect
The rest of the methods implemented by DataInputStream are variations of the read method for different fundamental data types. The type read by each method is easily identifiable by the name of the method. PRIVATE MACROBUTTON HtmlDirect
The FileInputStream Class
The FileInputStream class is useful for performing simple file input. For more advanced file input operations, you will more than likely want to use the RandomAccessFile class, which is discussed a little later in this chapter. The FileInputStream class can be instantiated using one of three following constructors: PRIVATE MACROBUTTON HtmlDirect
FileInputStream(String name)
FileInputStream(File file)
FileInputStream(FileDescriptor fdObj)
The first constructor takes a String object parameter called name, which specifies the name of the file to use for input. The second constructor takes a File object parameter that specifies the file to use for input. Youll learn more about the File object near the end of this chapter. The third constructor for FileInputStream takes a FileDescriptor object as its only parameter. PRIVATE MACROBUTTON HtmlDirect
The FileInputStream class functions exactly like the InputStream class, except that it is geared toward working with files. Listing 20.6 contains the ReadFile program, which uses the FileInputStream class to read data from a text file. ReadFile can be found in the file ReadFile.java on the CD-ROM. PRIVATE MACROBUTTON HtmlDirect
Listing 20.6. The ReadFile class.
import java.io.*;class ReadFile { public static void main (String args[]) { byte buf[] = new byte[64]; try { FileInputStream in = new FileInputStream(Grocery.txt); in.read(buf, 0, 64); } catch (Exception e) { System.out.println(Error: + e.toString()); } String s = new String(buf, 0); System.out.println(s); }}
PRIVATE MACROBUTTON HtmlDirect
In ReadFile, a FileInputStream object is first created by passing a string with the name of the file (Grocery.txt) as the input file. The read method is then called to read from the input file into a byte array. The byte array is then used to create a String object, which is in turn used for output. Pretty simple! PRIVATE MACROBUTTON HtmlDirect
The StringBufferInputStream Class
The StringBufferInputStream class, aside from having a very long name, is a pretty neat class. StringBufferInputString enables you to use a string as a buffered source of input. StringBufferInputStream implements all the same methods defined by InputStream, and no more. The StringBufferInputStream class has a single constructor, which follows: PRIVATE MACROBUTTON HtmlDirect
StringBufferInputStream(String s)
The constructor takes a String object, which it constructs the string buffer input stream out of. Although StringBufferInputStream doesnt define any additional methods, it does provide a few of its own member variables, which follow: PRIVATE MACROBUTTON HtmlDirect
String buffer
int count
int pos
The buffer string member is the buffer where the string data is actually stored. The count member variable specifies the number of characters to use in the buffer. Finally, the pos member variable keeps up with the current position in the buffer. Like the BufferedInputStream class, you will probably never see these member variables, but they are important in understanding how the StringBufferInputStream class is implemented. PRIVATE MACROBUTTON HtmlDirect
Listing 20.7 contains the ReadString program, which uses a StringBufferInputStream to read data from a string of text data. ReadString can be found in the file ReadString.java on the CD-ROM. PRIVATE MACROBUTTON HtmlDirect
Listing 20.7. The ReadString class.
import java.io.*;class ReadString { public static void main (String args[]) { // Get a string of input from the user byte buf1[] = new byte[64]; try { System.in.read(buf1, 0, 64); } catch (Exception e) { System.out.println(Error: + e.toString()); } String s1 = new String(buf1, 0); // Read the string as a string buffer and output it StringBufferInputStream in = new StringBufferInputStream(s1); byte buf2[] = new byte[64]; try { in.read(buf2, 0, 64); } catch (Exception e) { System.out.println(Error: + e.toString()); } String s2 = new String(buf2, 0); System.out.println(s2); }}
PRIVATE MACROBUTTON HtmlDirect
The ReadString program enables the user to type in text, which is read and stored in a string. This string is then used to create a StringBufferInputStream that is read into another string for output. Obviously, this program goes to a lot of trouble to do very little; its only meant as a demonstration of how to use the StringBufferInputStream class. Knowing this, its up to you to find an interesting application to apply this class to. PRIVATE MACROBUTTON HtmlDirect
The first half of the ReadString program should look pretty familiar; its essentially the guts of the ReadKeys3 program, which reads data entered by the keyboard into a string. The second half of the program is where you actually get busy with the StringBufferInputStream object. A StringBufferInputStream object is created using the String object (s1) containing the text entered from the keyboard. The contents of the StringBufferInputStream object are then read into a byte array using the read method. The byte array is in turn used to construct another String object (s2), which is output to the screen. PRIVATE MACROBUTTON HtmlDirect
Output Stream Classes
In Java, output streams are the logical counterparts to input streams and handle writing data to output sources. Using the water analogy from the discussion of input streams earlier, an output stream would be equivalent to the water spout on your bathtub. Just as water travels from a water plant through the pipes and out of the spout into your bathtub, so must data flow from an input device through the operating system and out of an output device. A leaky water spout is an even better way to visualize the transfer of data out of an output stream; each drop of water falling out of the spout represents a byte of data. Each byte of data flows to the output device just like the drops of water falling one after the next out of the bathtub spout. PRIVATE MACROBUTTON HtmlDirect
Getting back to Java, you use output streams to output data to various different output devices, such as the screen. The primary output stream classes used in Java programming follow: PRIVATE MACROBUTTON HtmlDirect
OutputStream
PrintStream
BufferedOutputStream
DataOutputStream
FileOutputStream
The Java output streams provide a variety of ways to output data. The OutputStream class defines the core behavior required of an output stream. The PrintStream class is geared toward outputting text data, such as the data sent to the standard output stream. The BufferedOutputStream class is an extension to the OutputStream class that provides support for buffered output. The DataOutputStream class is useful for outputting primitive data types such as int or float. And finally, the FileOutputStream class provides the support necessary to output data to files. PRIVATE MACROBUTTON HtmlDirect
The OutputStream Class
The OutputStream class is the output counterpart to InputStream and serves as an abstract base class for all the other output stream classes. OutputStream defines the basic protocol for writing streamed data to an output device. Like the methods for InputStream, you will become accustomed to the methods defined by OutputStream, because they act very much the same in every OutputStream derived class. The benefit of this common interface is that you can essentially learn a method once and then be able to apply it to different classes without starting the learning process over again. PRIVATE MACROBUTTON HtmlDirect
You will typically create an OutputStream derived object and call an appropriate method to tell it you want to output information. The OutputStream class uses a technique similar to the one used by InputStream; it will block until data has been written to an output device. While blocking (waiting for the current output to be processed), the OutputStream class will not allow any further data to be output. PRIVATE MACROBUTTON HtmlDirect
The OutputStream class implements the following methods: PRIVATE MACROBUTTON HtmlDirect
abstract void write(int b)
void write(byte b[])
void write(byte b[], int off, int len)
void flush()
void close()
OutputStream defines three different write methods for writing data in a few different ways. The first write method writes a single byte to the output stream, as specified by the integer parameter b. The second version of write takes an array of bytes as a parameter and writes them to the output stream. The last version of write takes a byte array, an integer offset, and a length as parameters. This version of write is very much like the second version, except it uses the other parameters to determine where in the byte array to begin outputting data, along with how much data to output. The off parameter specifies an offset into the byte array to begin outputting data from, and the len parameter specifies how many bytes are to be output. PRIVATE MACROBUTTON HtmlDirect
The flush method is used to flush the output stream. Calling flush will force the OutputStream object to output any pending data. PRIVATE MACROBUTTON HtmlDirect
Finally, the close method closes an output stream and releases any resources associated with the stream. Like InputStream objects, it isnt usually necessary to call close on an OutputStream object, because streams are automatically closed when they are destroyed. PRIVATE MACROBUTTON HtmlDirect
The PrintStream Class
The PrintStream class is derived from OutputStream and is designed primarily for printing output data as text. PrintStream has two different constructors: PRIVATE MACROBUTTON HtmlDirect
PrintStream(OutputStream out)
PrintStream(OutputStream out, boolean autoflush)
Both PrintStream constructors take an OutputStream object as their first parameter. The only difference between the two methods is how the newline character is handled. In the first constructor, the stream is flushed based on an internal decision by the object. In the second constructor, you can specify that the stream be flushed every time it encounters a newline character. You specify this through the Boolean autoflush parameter. PRIVATE MACROBUTTON HtmlDirect
The PrintStream class also implements a rich set of methods, which follow: PRIVATE MACROBUTTON HtmlDirect
boolean checkError()
void print(Object obj)
synchronized void print(String s)
synchronized void print(char s[])
void print(char c)
void print(int i)
void print(long l)
void print(float f)
void print(double d)
void print(boolean b)
void println()
synchronized void println(Object obj)
synchronized void println(String s)
synchronized void println(char s[])
synchronized void println(char c)
synchronized void println(int I)
synchronized void println(long l)
synchronized void println(float f)
synchronized void println(double d)
synchronized void println(boolean b)
The checkError method flushes the stream and returns whether or not an error has occurred. The return value of checkError is based on an error ever having occurred on the stream, meaning that once an error occurs, checkError will always return true for that stream. PRIVATE MACROBUTTON HtmlDirect
PrintStream provides a variety of print methods to handle all your printing needs. The version of print that takes an Object parameter simply outputs the results of calling the toString method on the object. The other print methods each take a different type parameter that specifies which data type is printed for each. PRIVATE MACROBUTTON HtmlDirect
The println methods implemented by PrintStream are very similar to the print methods. The only difference is that the println methods print a newline character following the data that is printed. The println method that takes no parameters simply prints a newline character by itself. PRIVATE MACROBUTTON HtmlDirect
The System.out Object
The monitor is the primary output device on modern computer systems. The System class has a member variable that represents the standard output stream, which is typically the monitor. The member variable is called out and is an instance of the PrintStream class. out is very useful for outputting text to the screen. But you already know this because youve seen the out member variable in most of the sample programs developed thus far. PRIVATE MACROBUTTON HtmlDirect
The BufferedOutputStream Class
The BufferedOutputStream class, which is very similar to the OutputStream class, provides a buffered stream of output. This enables you to write to a stream without causing a bunch of writes to an output device. The BufferedOutputStream class maintains a buffer that is written to when you write to the stream. When the buffer gets full or when it is explicitly flushed, it is written to the output device. This output approach is much more efficient since most of the data transfer is taking place in memory. And when it does come time to output the data to a device, it all happens at once. PRIVATE MACROBUTTON HtmlDirect
The BufferedOutputStream class implements the same methods defined in OutputStream, meaning that there are no additional methods, except for constructors. The two constructors for BufferedOutputStream follow: PRIVATE MACROBUTTON HtmlDirect
BufferedOutputStream(OutputStream out)
BufferedOutputStream(OutputStream out, int size)
Both constructors for BufferedOutputStream take an OutputStream object as their first parameter. The only difference between the two is the size of the internal buffer used to store the output data. In the first constructor, a default buffer size is used, where in the second constructor you specify the buffer size with the size integer parameter. The buffer itself within the BufferedOutputStream class is managed by two member variables, which follow: PRIVATE MACROBUTTON HtmlDirect
byte buf[]
int count
The buf byte array member variable is the actual data buffer where output data is stored. The count member keeps up with how many bytes are in the buffer. These two member variables are sufficient to represent the state of the output stream buffer. PRIVATE MACROBUTTON HtmlDirect
Listing 20.8 contains the WriteStuff program, which uses a BufferedOutputStream object to output a byte array of text data. WriteStuff can be found in the file WriteStuff.java on the CD-ROM. PRIVATE MACROBUTTON HtmlDirect
Listing 20.8. The WriteStuff class.
import java.io.*;class WriteStuff { public static void main (String args[]) { // Copy the string into a byte array String s = new String(Dance, spider!\n); byte[] buf = new byte[64]; s.getBytes(0, s.length(), buf, 0); // Output the byte array (buffered) BufferedOutputStream out = new BufferedOutputStream(System.out); try { out.write(buf, 0, 64); out.flush(); } catch (Exception e) { System.out.println(Error: + e.toString()); } }}
PRIVATE MACROBUTTON HtmlDirect
The WriteStuff program fills a byte array with text data from a string and outputs the byte array to the screen using a buffered output stream. WriteStuff begins by creating a String object containing text, and a byte array. The getBytes method of String is used to copy the bytes of data in the string to the byte array. The getBytes method copies the low byte of each character in the string to the byte array. This works because the Unicode representation of ASCII characters has zeros in the high byte. Once the byte array is ready, a BufferedOutputStream object is created by passing System.out into the constructor. The byte array is then written to the output buffer using the write method. Since the stream is buffered, it is necessary to call the flush method to actually output the data. PRIVATE MACROBUTTON HtmlDirect
The DataOutputStream Class
The DataOutputStream class is useful for writing primitive Java data types to an output stream in a portable way. DataOutputStream only has one constructor, which simply takes an OutputStream object as its only parameter. This constructor is defined as follows: PRIVATE MACROBUTTON HtmlDirect
DataOutputStream(OutputStream out)
The DataOutputStream class implements the following useful methods beyond those inherited from OutputStream: PRIVATE MACROBUTTON HtmlDirect
final int size()
final void writeBoolean(boolean v)
final void writeByte(int v)
final void writeShort(int v)
final void writeChar(int v)
final void writeInt(int v)
final void writeLong(long v)
final void writeFloat(float v)
final void writeDouble(double v)
final void writeBytes(String s)
final void writeChars(String s)
The size method is used to determine how many bytes have been written to the stream thus far. The integer value returned by size specifies the number of bytes written. PRIVATE MACROBUTTON HtmlDirect
The rest of the methods implemented in DataOutputStream are all variations on the write method. Each different version of writeType takes a different data type that is in turn written as output. PRIVATE MACROBUTTON HtmlDirect
The FileOutputStream Class
The FileOutputStream class provides a means to perform simple file output. For more advanced file output, you should check out the RandomAccessFile class, which is discussed a little later in this chapter. A FileOutputStream object can be created using one of the three following constructors: PRIVATE MACROBUTTON HtmlDirect
FileOutputStream(String name)
FileOutputStream(File file)
FileOutputStream(FileDescriptor fdObj)
The first constructor takes a String parameter, which specifies the name of the file to use for input. The second constructor takes a File object parameter that specifies the input file. Youll learn about the File object a little later in this chapter. The third constructor takes a FileDescriptor object as its only parameter. PRIVATE MACROBUTTON HtmlDirect
The FileOutputStream class functions exactly like the OutputStream class, except that it is specifically designed to work with files. Listing 20.9 contains the WriteFile program, which uses the FileOutputStream class to write user input to a text file. WriteFile can be found in the file WriteFile.java on the CD-ROM. PRIVATE MACROBUTTON HtmlDirect
Listing 20.9. The WriteFile class.
import java.io.*;class WriteFile { public static void main (String args[]) { // Read the user input byte buf[] = new byte[64]; try { System.in.read(buf, 0, 64); } catch (Exception e) { System.out.println(Error: + e.toString()); } // Output the data to a file try { FileOutputStream out = new FileOutputStream(Output.txt); out.write(buf); } catch (Exception e) { System.out.println(Error: + e.toString()); } }}
PRIVATE MACROBUTTON HtmlDirect
In WriteFile, user input is read from the standard input stream into a byte array using the read method of InputStream. A FileOutputStream object is then created with a filename of Output.txt 4", which is passed in as the only parameter to the constructor. The write method is then used to output the byte array to the stream. You can see that working with output file streams is just as easy as working with input file streams. PRIVATE MACROBUTTON HtmlDirect
File Classes
If the FileInputStream and FileOutputStream classes dont quite meet up to your file handling expectations, dont despair! Java provides two more classes for working with files that are sure to meet your needs. These two classes are File and RandomAccessFile. The File class basically models an operating system directory entry, enabling you access to information about a file including file attributes and the full path where the file is located, among other things. The RandomAccessFile class, on the other hand, provides a variety of methods for reading and writing data to and from a file. PRIVATE MACROBUTTON HtmlDirect
The File Class
The File class can be instantiated using one of three constructors, which follow: PRIVATE MACROBUTTON HtmlDirect
File(String path)
File(String path, String name)
File(File dir, String name)
The first constructor takes a single String parameter that specifies the full path name of the file. The second constructor takes two String parameters: path and name. The path parameter specifies the directory path where the file is located, while the name parameter specifies the name of the file. The third constructor is similar to the second, except it takes another File object as the first parameter instead of a string. The File object in this case is used to specify the directory path of the file. PRIVATE MACROBUTTON HtmlDirect
The most important methods implemented by the File class follow: PRIVATE MACROBUTTON HtmlDirect
String getName()
String getPath()
String getAbsolutePath()
String getParent()
boolean exists()
boolean canWrite()
boolean canRead()
boolean isFile()
boolean isDirectory()
boolean isAbsolute()
long lastModified()
long length()
boolean mkdir()
boolean mkdirs()
boolean renameTo(File dest)
boolean delete()
String[] list()
String[] list(FilenameFilter filter)
The getName method gets the name of a file and returns it as a string. The getPath method returns the path of a file, which may be relative, as a string. The getAbsolutePath method returns the absolute path of a file. The getParent method returns the parent directory of a file, or null if a parent directory is not found. PRIVATE MACROBUTTON HtmlDirect
The exists method returns a Boolean specifying whether or not a file actually exists. The canWrite and canRead methods return Boolean values the specify whether a file can be written to or read from. The isFile and isDirectory methods return Boolean values the specify if a file is valid and if the directory information is valid. The isAbsolute method returns a Boolean value specifying if a filename is absolute. PRIVATE MACROBUTTON HtmlDirect
The lastModified method returns a long value that specifies the time in which a file was last modified. The long value returned is only useful in determining differences between modification times; it has no meaning as an absolute time and is not suitable for output. The length method returns the length of a file in bytes. PRIVATE MACROBUTTON HtmlDirect
The mkdir method creates a directory based on the current path information. mkdir returns a Boolean indicating the success of creating the directory. The mkdirs method is similar to mkdir, except that it can be used to create an entire directory structure. The renameTo method renames a file to the name specified by the File object passed as the dest parameter. The delete method deletes a file. Both renameTo and delete return a Boolean value indicating success or failure. PRIVATE MACROBUTTON HtmlDirect
Finally, the list methods of the File object obtain listings of the directory contents. Both list methods return a list of filenames in a String array. The only difference between the two is that the second version takes a FilenameFilter object that enables you to filter out certain files from the list. PRIVATE MACROBUTTON HtmlDirect
Listing 20.10 contains the source code for the FileInfo program, which uses a File object to determine information about a file in the current directory. The FileInfo program is located in the FileInfo.java source file on the CD-ROM. PRIVATE MACROBUTTON HtmlDirect
Listing 20.10. The FileInfo class.
import java.io.*;class FileInfo { public static void main (String args[]) { System.out.println(Enter file name: ); char c; StringBuffer buf = new StringBuffer(); try { while ((c = (char)System.in.read()) != \n) buf.append(c); } catch (Exception e) { System.out.println(Error: + e.toString()); } File file = new File(buf.toString()); if (file.exists()) { System.out.println(File Name : + file.getName()); System.out.println( Path : + file.getPath()); System.out.println(Abs. Path : + file.getAbsolutePath()); System.out.println(Writable : + file.canWrite()); System.out.println(Readable : + file.canRead()); System.out.println(Length : + (file.length() / 1024) + KB); } else System.out.println(Sorry, file not found.); }}
PRIVATE MACROBUTTON HtmlDirect
The FileInfo program uses the File object to get information about a file in the current directory. The user is first prompted to type in a filename, with the resulting input being stored in a String object. The String object is then used as the parameter to the File objects constructor. A call to the exists method determines if the file actually exists. If so, information about the file is obtained through the various File methods and the results output to the screen. PRIVATE MACROBUTTON HtmlDirect
The RandomAccessFile Class
The RandomAccessFile class provides a multitude of methods for reading and writing to files. Although you can certainly use FileInputStream and FileOutputStream for file I/O, RandomAccessFile provides many more features and options. Following are the constructors for RandomAccessFile: PRIVATE MACROBUTTON HtmlDirect
RandomAccessFile(String name, String mode)
RandomAccessFile(File file, String mode)
The first constructor takes a String parameter specifying the name of the file to access, along with a String parameter specifying the type of mode (read or write). The mode type can be either r for read mode, or rw for read/write mode. The second constructor takes a File object as the first parameter, which specifies the file to access. The second parameter is a mode string, which works exactly the same as in the first constructor. PRIVATE MACROBUTTON HtmlDirect
The RandomAccessFile class implements a variety of powerful file I/O methods. Following are some of the most useful ones: PRIVATE MACROBUTTON HtmlDirect
int skipBytes(int n)
long getFilePointer()
void seek(long pos)
int read()
int read(byte b[])
int read(byte b[], int off, int len)
final boolean readBoolean()
final byte readByte()
final int readUnsignedByte()
final short readShort()
final int readUnsignedShort()
final char readChar()
final int readInt()
final long readLong()
final float readFloat()
final double readDouble()
final String readLine()
final void readFully(byte b[])
final void readFully(byte b[], int off, int len)
void write(byte b[])
void write(byte b[], int off, int len)
final void writeBoolean(boolean v)
final void writeByte(int v)
final void writeShort(int v)
final void writeChar(int v)
final void writeInt(int v)
final void writeLong(long v)
void writeFloat(float v)
void writeDouble(double v)
void writeBytes(String s)
void writeChars(String s)
long length()
void close()
From looking at this method list, you no doubt are thinking that many of these methods look familiar. And they should look familiar; most of the methods implemented by RandomAccessFile are also implemented by either FileInputStream or FileOutputStream. The fact that RandomAccessFile combines them into a single class is a convenience in and of itself. But you already know how to use these methods because they work just like they do in FileInputStream and FileOutputStream. What you are interested in are the new methods implemented by RandomAccessFile. PRIVATE MACROBUTTON HtmlDirect
The first new method you might have noticed is the getFilePointer method. getFilePointer returns the current position of the file pointer as a long value. The file pointer indicates the location in the file where data will be read from or written to next. In read mode, the file pointer is analogous to the needle on a phonograph or the laser in a CD player. The seek method is the other new method that should catch your attention. seek sets the file pointer to the absolute position specified by the long parameter pos. Calling seek to move the file pointer is analogous to moving the phonograph needle with your hand. In both cases, the read point of the data or music is being moved. It is a similar situation when you are writing data as well. PRIVATE MACROBUTTON HtmlDirect
Listing 20.11 contains the source code for FilePrint, which is a program that uses the RandomAccessFile class to print a file to the screen. The source code for the FilePrint program can be found in the file FilePrint.java on the CD-ROM. PRIVATE MACROBUTTON HtmlDirect
Listing 20.11. The FilePrint class.
import java.io.*;class FilePrint { public static void main (String args[]) { System.out.println(Enter file name: ); char c; StringBuffer buf = new StringBuffer(); try { while ((c = (char)System.in.read()) != \n) buf.append(c); RandomAccessFile file = new RandomAccessFile(buf.toString(), rw); while (file.getFilePointer() < file.length()) System.out.println(file.readLine()); } catch (Exception e) { System.out.println(Error: + e.toString()); } }}
PRIVATE MACROBUTTON HtmlDirect
The FilePrint program begins very much like the FileInfo program in that it prompts the user to type in a filename and stores the result in a string. It then uses that string to create a RandomAccessFile object in read/write mode, which is specified by passing rw as the second parameter to the constructor. A while loop is then used to repeatedly call the readLine method until the entire file has been read. The call to readLine is performed within a call to println so that each line of the file is output to the screen. PRIVATE MACROBUTTON HtmlDirect
Summary
Whew, this chapter covered a lot of ground! Hopefully youve managed to make it this far relatively unscathed. On the up side, youve learned about all there is to know about fundamental Java I/O and the most important classes in the I/O package. Thats not to say that there isnt still a wealth of information inside the I/O package that you havent seen. The point is that the Java class libraries are very extensive, which means that some of the classes will only be useful under very special circumstances. The goal of this chapter was to highlight the more mainstream classes and methods within the I/O package. PRIVATE MACROBUTTON HtmlDirect
If you think youve had enough talk about I/O, then maybe youre ready for the next phase of Java: applet programming. Youve survived this far, so you might as well push on and start reaping the real benefits of knowing the Java language and class libraries inside and out. The next section of the book is focused on applet programming, which enables you to embed graphical Java applications into HTML pages. Have fun! PRIVATE MACROBUTTON HtmlDirect
Chapter 21
Applet programming preview
One of the major uses of Java is the creation of miniapplications, or applets, which are designed to be small, fast, and easily transferable over network resources. These applets can be thought of as small programs that might be more focused in scope than a full-blown application. For example, an application might be a spreadsheet. A full-blown spreadsheet would enable users to specify a variety of calculations and functions, from amortizing loans to keeping fullfinancial records for a small business. An applet, on the other hand, might be limited to a loan calculator, figuring interest and loan payments. Rather than trying to do it all, like anapplication, applets generally focus on one small task or a component of a task. Instead ofbeing limited and narrow, applets are streamlined and more efficient. PRIVATE MACROBUTTON HtmlDirect
What Is an Applet?
Quite simply, applets are compiled Java programs that are run using the Applet Viewer or through any World Wide Web browser that supports Java. What an applet does is up to you. It can display graphics, play sounds, accept user input, and manipulate data just like any program. This section is designed to help you understand what goes into creating an applet and how applets can function in conjunction with the Internet and the World Wide Web. PRIVATE MACROBUTTON HtmlDirect
Technically an applet is a subclass of java.awt.Panel. Being such, an applet can contain features from the Abstract Window Toolkit and the Java Language Package. To aid in the creation of applets, Sun also has developed the Java Applet Package, a collection of constructs and methods designed to make a number of useful features accessible to programmers. PRIVATE MACROBUTTON HtmlDirect
Applets and the World Wide Web
Applets were not conceived for use with the Internet, instead they were designed for use with hand-held computing devices, or Personal Digital Assistants. However, the basic properties of applets have made them a perfect fit for use on the Internet and the World Wide Web. Because applets are small, they are downloaded and launched very quickly. Applets can add new levels of functionality and interactivity to Web pages without the overhead of full-scale applications. With the recent introduction of Java-capable browsers such as Netscape, applets have begun to make a serious impact on the World Wide Web. PRIVATE MACROBUTTON HtmlDirect
More Web pages are now featuring Java applets for a variety of uses. Some of the ways applets are currently being used on the World Wide Web include the following: PRIVATE MACROBUTTON HtmlDirect
Animation
Displaying images with sound
Graphic effects, such as scrolling text
Interactive programming, such as games
Java applets take special advantage of the features already built into Web browsers, enabling programmers to obtain a rich feature set with a minimum of code. For example, to incorporate GIF or JPEG files into a Java applet, it is not necessary to write any decoding methods for the image files. Applets can use the browsers decoder to display image files. Using the browser to display images makes applets easily extensible. If a new image format becomes popular and is incorporated into a browser, the Java applet will automatically be able to handle that format. It isnt necessary for the applet programmer to change the applet significantly to access new formats. Applets are well-suited to the World Wide Web because they leverage browser features to decrease size, increase download speed, and simplify applet programming. PRIVATE MACROBUTTON HtmlDirect PRIVATE MACROBUTTON HtmlDirect *
PRIVATE MACROBUTTON HtmlDirect *NOTEAt the time of this writing, the only browser currently supporting Java is the Netscape Navigator 2.0. Because of this, the text concentrates on how Java takes advantage of Netscapes features, some of which are currently unique to Netscape. This is not meant to be an endorsement of Netscape, and certainly as Java begins to broaden its scope other browsers will add to Javas functionality as well.How Applets Differ from Applications
Applets can be quite robust programs; however, there are significant differences between applets and applications. Applets are not full-featured applications. There are concrete and implicit limitations that need to be considered in designing and creating applets. For example: PRIVATE MACROBUTTON HtmlDirect
Applets leverage browsers
Applets have limited file access
Applets have limited network access
Weve already described how applets leverage Web browsers to provide functionality over applications. However, the nature of applets warrants some important restrictions on their functionality in the interest of security. PRIVATE MACROBUTTON HtmlDirect
The Limits of Applets
Because applets can be downloaded over the Web, they are, by nature, not secure. Applets are precompiled bytecode. The compiled bytecode is downloaded to your machine and executed locally. Because of this, both Sun and browser manufacturers have placed some restrictions on the functionality of applets. Unfortunately, while these restrictions limit what an applet iscapable of, they are not meant to hinder the development of applets. Instead, theserestrictions are meant to ensure the security of machines that will run applets by preventing applets from being used maliciously. This security was implemented to help them gain wide acceptance on the Net. PRIVATE MACROBUTTON HtmlDirect
Functional Limits
Applets are downloaded from their home servers as bytecode. This is what makes Java easily portable from platform to platform. The bytecode is platform-independent, and is executed through the Applet Viewer or a Java-capable Web browser. Because the bytecode is executed on a users local machine, there needs to be some level of security to make sure that the integrity of the machine is not compromised. PRIVATE MACROBUTTON HtmlDirect
One of the ways that Java accomplishes this is through a verification process to ensure that the bytecode does not violate any Java language conventions. In order to perform verification, any methods or variables must be called by name. Calling methods by name allows verification of all the methods and variables in the bytecode, and ensures that an applet is not accessing memory areas that might contain the OS or other applications. Limiting functions to call-by-name also has the advantage of eliminating memory pointers, and anyone who has struggled with pointers in C or C++ can testify that pointers are one of the most commonly misunderstood aspects of programming. The elimination of pointers is not without a priceimplementing all methods and variables by name slows down Java applets when compared to other programming languages. PRIVATE MACROBUTTON HtmlDirect
Applets are not given full access to the local machines file system. Applets currently do not have the means to save files out to a users local machine, and they cant read files off the local machine either. Though this does limit the functionality of applets significantly, allowing applets access to a local file system would represent a serious security hole. For example, if an applet could read files on a system, it could potentially send information from those files back to the applets author. If an applet could write files to a system, it could potentially become a carrier for viruses. Rather than risk security, applets are simply prevented from accessing files. Undoubtedly, file access would increase the functionality of applets and the end goal is to allow applets to read and save files. There are various ways this might be accomplished, but until more security methods are implemented, applets are prevented from file system access. PRIVATE MACROBUTTON HtmlDirect
Applets also are restricted from loading dynamic or shared libraries from other programming languages. Java has the capability to declare methods as being native, which allows the virtual machine to take advantage of other language libraries such as C or C++. However, because these libraries cant be verified and they would require access to the file system, applets are not allowed to use dynamic libraries. The end goal is to optimize Java to the point where all of the dynamic libraries could be written in Java and the need for other language libraries would be eliminated. As the language grows and evolves, many of these limitations will be removed. For now, they are the price of participating so closely in the evolution of a new language. PRIVATE MACROBUTTON HtmlDirect
Limitations Imposed by the Browser
In addition to the limitations imposed by the language itself, the browser that executes applet bytecode also places some restrictions on applets. A Web browser is a trusted applicationa user has chosen to load the browser on the local machine and trusts that it will not damage any files or the operating system. Applets are untrusted applications. They are downloaded immediately and are executed on a machine without receiving the users consent. (The user might choose to use a Java-capable browser, and therefore imply consent, but the user cant approve individual applets.) Because of this, Java-capable browsers have placed some restrictions on applets in order to ensure that they dont violate system integrity inadvertently. PRIVATE MACROBUTTON HtmlDirect
The most important limitation placed on an applet by the Web browser is network connectivity. Applets currently are limited to network connections with their host machines. This means your Java applet can communicate directly back to the Web server that its downloaded from, but it cannot contact any other servers on the Net. Networking also comes back to the issue of security. By restricting access back to the applets original host, applets are provided basic network functionality with a minimum security risk. If applets were allowed to contact any server on the Net, applets could perform some potentially dangerous tasks. PRIVATE MACROBUTTON HtmlDirect
For example, if an applet was allowed to contact any server, it would be possible to make a connection to any e-mail server. An applet could then masquerade as your machine and send forged mail that would appear to be coming from you. The issue of network connectivity for applets is widely debated among Java developers. It is still possible to write a number of applets that take advantage of network connections to their own servers. Though restricting network connectivity imposes some limits on applets, it is being done in the interest of security. Certainly, as better security methods are developed, network connectivity will increase and applets will become more functional. For more information on Java security issues, see Chapter 40. PRIVATE MACROBUTTON HtmlDirect
Applet Basics
The object-oriented nature of Java is instrumental in understanding what defines an applet from a technical standpoint. Because of the hierarchy of the Java classes, an applet is an extension of the Panel object in the Abstract Windows Toolkit (AWT). A panel is a subclass of the Container class (see Figure 21.1), and as such can contain any Java language components, such as buttons, menus, scroll bars, and so on. PRIVATE MACROBUTTON HtmlDirect
Because an applet actually is a class, applets can be used to build other applets or full-blown applications. Just as your applets can be used within other applets, they also inherit features from the classes above them. PRIVATE MACROBUTTON HtmlDirect
Applets also have distinct stages in their lifetime. These stages include init, start, stop, and destroy. All of these methods can be overwritten by the applet programmer to accomplish specific tasks during each stage in an applets lifetime. PRIVATE MACROBUTTON HtmlDirect PRIVATE href="049-5g/21/Figure 21.gif"MACROBUTTON HtmlResAnchor PRIVATE border=0 alt="Figure" src="figicon.gif" MACROBUTTON HtmlResImg INCLUDEPICTURE "C:/WINDOWS/TEMP/wia224/figicon15.bmp" \* MERGEFORMAT FIGURE 21.1. PRIVATE MACROBUTTON HtmlDirect
The Java class hierarchies.
Here is a breakdown of the four stages: PRIVATE MACROBUTTON HtmlDirect
init(); PRIVATE MACROBUTTON HtmlDirect
The init stage consists of initializing any methods and variables the applet needs to function, such as images to be loaded. The init method is called when the applet is first loaded. PRIVATE MACROBUTTON HtmlDirect
start(); PRIVATE MACROBUTTON HtmlDirect
The start stage starts the primary functions of an applet. For example, if an applet plays a sound, it could start playing during the start stage. The start method is called when the init method has finished and the applet is ready to execute. PRIVATE MACROBUTTON HtmlDirect
stop(); PRIVATE MACROBUTTON HtmlDirect
The stop stage can be used to stop any actions that might still be in progress from the start stage when an applet is exited. For example, a sound loop would need to be stopped when a person left the Web page containing a sound applet. The stop method is called when the page is left, or the browser is minimized. PRIVATE MACROBUTTON HtmlDirect
destroy(); PRIVATE MACROBUTTON HtmlDirect
Destroy is called automatically, and completes any memory cleanup or garbage collection that needs to be done when an applet is destroyed. It can be overwritten, but this is not generally necessary. The destroy method is called when you quit a browser. PRIVATE MACROBUTTON HtmlDirect
Inheriting from the Applet Class
Applets inherit the properties of the Panel object in the AWT, and the Applet class attributes from java.applet.Applet. This is evident in the way that all Java applets are structured. In defining the initial applet, PRIVATE MACROBUTTON HtmlDirect
public class Classname extends java.applet.Applet { } PRIVATE MACROBUTTON HtmlDirect
the code shows how your applet class is an extension of the Applet class. There are a number of methods that are built into the Applet class to make developing applets easier and these are the subject of Chapter 23, The Applet Package and Graphics. PRIVATE MACROBUTTON HtmlDirect
The idea of inheritance is fundamental to the structure of applets. Applets inherit thecapability to contain user interface objects because all applets are Panels. Applets inherit a great deal of their functionality from the Applet class. PRIVATE MACROBUTTON HtmlDirect
Applet HTML
Applets currently can be viewed on several UNIX platforms, Windows 95, and Windows NT. The Java world is continuing to expand, and soon Java will be available for more popular platforms. Once your Java code has been compiled, it can be executed with the Applet Viewer, or through any Java-capable browser. Applets require the following two components to execute: PRIVATE MACROBUTTON HtmlDirect
The compiled bytecode
An HTML file containing basic applet information and parameters
The compiled bytecode is the executable component of the applet. The HTML file is required by both the Applet Viewer and any Web browser in order to execute the code properly. The HTML file is based on the | | | | | | | | | |