Java NIO Channel
- You can both read and write to a Channels. Streams are typically one-way (read or write).
- Channels can be read and written asynchronously.
- Channels always read to, or write from, a Buffer.
As mentioned above, you read data from a channel into a buffer, and write data from a buffer into a channel. Here is an illustration of that:
Java NIO Channel和Stream非常类似,除了以下几点不同:
- 可以同时从一个Channel中读取和写入数据,而Stream却是单工方式(一个Stream要么是读,要么是写)。
- Channel可以异步的进行读或写。
- Channel总是将数据读取到Buffer中,或者从Buffer写入数据。
如上所述,你可以从Channel读取数据到Buffer,并且可以将Buffer的数据写入到Channel。下面是一个示意图:
Java NIO: Channels read data into Buffers, and Buffers write data into Channels |
Channel Implementations
Here are the most important Channel implementations in Java NIO:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
The FileChannel
reads data from and to files.
The DatagramChannel
can read and write data over the network via UDP.
The SocketChannel
can read and write data over the network via TCP.
The ServerSocketChannel
allows you to listen for incoming TCP connections, like a web server does. For each incoming connection a SocketChannel
is created.
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
FileChannel能够读取或者写入数据到文件。
DatagramChannel能够通过UDP协议读取或者写入数据到网络。
SocketChannel能够通过TCP协议读取或者写入数据到网络。
ServerSocketChannel允许我们监听到来的TCP连接,就像一个Web服务器所做的一样。对每个到来的连接都会创建一个SocketChannel。
Basic Channel Example
Here is a basic example that uses a FileChannel
to read some data into a Buffer
:
下面是一个简单例子,用来说明如何使用FileChannel来读取数据到一个Buffer:
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = inChannel.read(buf); } aFile.close();
Notice the buf.flip()
call. First you read into a Buffer. Then you flip it. Then you read out of it. I'll get into more detail about that in the next text about Buffer
's.
注意buf.flip()方法的调用。首先我们读入数据到一个Buffer中,然后我们flip这个buffer,之后我们再从这个buffer中读出数据。在下一个章节我将详细说明这样做的原因。