Java Reference
In-Depth Information
Chapter 9
New Input/Output
In this chapter, you will learn
What the New Input/Ouput is
How to create different types of buffers
How to read data from buffers and write data to buffers
How to manipulate position, limit, and mark properties of a buffer
How to create different types of views of a buffer
How to encode/decode data in a buffer using different charsets
What channels are and how to use channels to read/write files' contents
How to use memory-mapped files for faster I/O
How to use file locks
How to know the byte order of a machine and how to deal with byte order when using buffers
What Is NIO?
The stream-based I/O uses streams to transfer data between a data source/sink and a Java program. The Java program
reads from or writes to a stream a byte at a time. This approach to performing I/O operations is slow. The New Input/
Ouput (NIO) solves the slow speed problem in the older stream-based I/O.
In NIO, you deal with channels and buffers for I/O operations. A channel is like a stream. It represents a
connection between a data source/sink and a Java program for data transfer. There is one difference between a
channel and a stream. A stream can be used for one-way data transfer. That is, an input stream can only transfer data
from a data source to a Java program; an output stream can only transfer data from a Java program to a data sink.
However, a channel provides a two-way data transfer facility. You can use a channel to read data as well as to write
data. You can obtain a read-only channel, a write-only channel, or a read-write channel depending on your needs.
In stream-based I/O, the basic unit of data transfer is a byte. In channel-based NIO, the basic unit of data transfer
is a buffer. A buffer is a bounded data container. That is, a buffer has a fixed capacity that determines the upper limit
of the data it may contain. In stream-based I/O, you write data directly to the stream. In channel-based I/O, you write
data into a buffer; you pass that buffer to the channel, which writes the data to the data sink. Similarly, when you want
to read data from a data source, you pass a buffer to a channel. The channel reads data from the data source into a
buffer. You read data from the buffer. Figure 9-1 depicts the interaction between a channel, a buffer, a data source, a
data sink, and a Java program. It is evident that the most important parts in this interaction are reading from a buffer
and writing into a buffer. I will discuss buffers and channels in detail in subsequent sections.
 
Search WWH ::




Custom Search