Input/output: A conceptual overview
I/O -- or input/output -- refers to the interface between a computer and the rest of the world, or between a single program and the rest of the computer. It is such a crucial element of any computer system that the bulk of any I/O is actually built into the operating system. Individual programs generally have most of their work done for them.
In Java programming, I/O has until recently been carried out using a stream metaphor. All I/O is viewed as the movement of single bytes, one at a time, through an object called a
Stream I/O is used for contacting the outside world. It is also used internally, for turning objects into bytes and then back into objects.
NIO has the same role and purpose as original I/O, but it uses a different metaphor -- block I/O. As you will learn in this tutorial, block I/O can be a lot more efficient than stream I/O.
NIO was created to allow Java programmers to implement high-speed I/O without having to write custom native code. NIO moves the most time-consuming I/O activities (namely, filling and draining buffers) back into the operating system, thus allowing for a great increase in speed.
The most important distinction between the original I/O library (found in
java.io.* ) and NIO has to do with how data is packaged and transmitted. As previously mentioned, original I/O deals with data in streams, whereas NIO deals with data in blocks.
A stream-oriented I/O system deals with data one byte at a time. An input stream produces one byte of data, and an output stream consumes one byte of data. It is very easy to create filters for streamed data. It is also relatively simply to chain several filters together so that each one does its part in what amounts to a single, sophisticated processing mechanism. On the flip side, stream-oriented I/O is often rather slow.
A block-oriented I/O system deals with data in blocks. Each operation produces or consumes a block of data in one step. Processing data by the block can be much faster than processing it by the (streamed) byte. But block-oriented I/O lacks some of the elegance and simplicity of stream-oriented I/O.
The original I/O package and NIO have been well integrated in JDK 1.4.
java.io.* has been reimplemented using NIO as its base, so it can now take advantage of some features of NIO. For example, some of the classes in the
java.io.* package contain methods to read and write data in blocks, which leads to faster processing even in more stream-oriented systems.
It is also possible to use the NIO library to implement standard I/O functions. For example, you could easily use block I/O to move data one byte at a time. But as you will see, NIO also offers many advantages that are not available from the original I/O package.