In the standard IO API you work with byte streams and character streams. In NIO you work with channels and buffers. Data is always read from a channel into a buffer, or written from a buffer to a channel.
Java NIO contains the concept of "selectors". A selector is an object that can monitor multiple channels for events (like: connection opened, data arrived etc.). Thus, a single thread can monitor multiple channels for data.
主要的Channel
FileChannel
DatagramChannel
SocketChannel
ServerSocketChannel
主要的Buffer
ByteBuffer
ShortBuffer
IntBuffer
LongBuffer
CharBuffer
DoubleBuffer
FloatBuffer
Java NIO Channels are similar to streams with a few differences:
1. You can both read and write to a Channels. Streams are typically one-way (read or write).
2. Channels can be read and written asynchronously.
3. Channels always read to, or write from, a Buffer.
Using a Buffer to read and write data typically follows this little 4-step process:
1. Write data into the Buffer.
2. Call buffer.flip()
3. Read data out of the Buffer
4. Call buffer.clear() or buffer.compact()
A Buffer has three properties:
1. capacity
2. position
3. limit
The meaning of position and limit depends on whether the Buffer is in read or write mode. Capacity always means the same, no matter the buffer mode.
To obtain a Buffer object you must first allocate it. Every Buffer class has an allocate() method that does this.
A scattering read from a channel is a read operation that reads data into more than one buffer. Thus, the channel "scatters" the data from the channel into multiple buffers.
A gathering write to a channel is a write operation that writes data from more than one buffer into a single channel. Thus, the channel "gather" the data from multiple buffers into one channel.
In Java NIO you can transfer data directly from one channel to another, if one of the channels is a FileChannel. The FileChannel class has a transferTo() and a transferFrom() method which does this for you.
Selector selector = Selector.open();
channel.configureBlocking(false);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
A FileChannel cannot be set into non-blocking mode. It always runs in blocking mode.
A Java NIO Pipe is a one-way data connection between two threads. A pipe has a source channel and a sink channel. You write data to the sink channel. This data can then be read from the source channel.
A Java Path instance represents a path in the file system. A path can point to either a file or a directory. A path can be absolute or relative.
The Java NIO Files class (java.nio.file.Files) provides several methods for manipulating files in the file system.