Input/Output

Input and output are performed in Java by means of streams. The same mechanism is used whether the information is being input or output by means of a file, terminal I/O, socket, or pipe. Separate streams are used for reading from a source and for writing to a destination or sink. For both these streams, the mechanism is open a stream, read or write information, and close the stream. The java.io package provides a large number of classes to handle the different physical I/O implementations. These are shown in Figures 1 to 4. J2SE 1.4 includes the java.nio, or ''New I/O," package. This supplements the existing java.io package and contains features such as buffering for primitive data types and mapping a file in memory. These subjects are beyond the scope of this book; in this chapter, we cover the
java.io package.

At the top level are InputStream and OutputStream. InputStream is an abstract class representing an input stream of bytes. This class has a number of methods, the most important of which are a number of overloaded read methods. OutputStream is an abstract class representing a output stream of bytes. This class has a number of methods, the most important of which are a number of overloaded write methods. A number of specialized classes are inherited from InputStream and OutputStream that override their parent methods to handle specific I/O implementations, for example, files or pipes. Figures 1 and 2 also show a number of subclasses of FilterInputStream and FilterOutputStream. These filter streams add functionality to existing streams, for example, providing buffering or letting an application read or write primitive Java data types. Similar to InputStream and OutputStream classes are the Reader and Writer classes. However, these are abstract classes that represent input and output streams of characters rather than bytes.


Figure:1: InputStream hierarchy


Figure:2: OutputStream hierarchy


Figure:3: Reader Hierarchy


Figure:4: Writer Hierarchy

No comments:

Post a Comment