Because default encoders and decoders are provided, you will not often need to work
explicitly withcharsets.
Aselectorsupports key-based, non-blocking, multiplexed I/O. In other words, selectors
enable you to perform I/O through multiple channels. Selectors are supported by classes
defined in thejava.nio.channelspackage. Selectors are most applicable to socket-backed
channels.
We will not use charsets or selectors in this chapter, but you might find them useful in
your own applications.
Using the NIO System
Because the most common I/O device is the disk file, the rest of this section examines how
to access a disk file using NIO. Because all file channel operations are byte-based, the type
of buffers that we will be using are of typeByteBuffer.
Reading a File
There are several ways to read data from a file using NIO. We will look at two. The first
reads a file by manually allocating a buffer and then performing an explicit read operation.
The second uses a mapped file, which automates the process.
To read a file using a channel and a manually allocated buffer, follow this procedure.
First, open the file for input usingFileInputStream. Then, obtain a channel to this file by
callinggetChannel( ). It has this general form:
FileChannel getChannel( )
It returns aFileChannelobject, which encapsulates the channel for file operations. Once
a file channel has been opened, obtain the size of the file by callingsize( ), shown here:
long size( ) throws IOException
It returns the current size, in bytes, of the channel, which reflects the underlying file. Next,
callallocate( )to allocate a buffer large enough to hold the file’s contents. Because file channels
operate on byte buffers, you will use theallocate( )method defined byByteBuffer. It has
this general form:
static ByteBuffer allocate(intcap)
Here,capspecifies the capacity of the buffer. A reference to the buffer is returned. After you
have created the buffer, callread( )on the channel, passing a reference to the buffer.
The following program shows how to read a text file calledtest.txtthrough a channel
using explicit input operations:
// Use NIO to read a text file.
import java.io.;
import java.nio.;
import java.nio.channels.*;
public class ExplicitChannelRead {
public static void main(String args[])
FileInputStream fIn;
Chapter 27: NIO, Regular Expressions, and Other Packages 819