Java NIO Channels are similar to streams with a few differences:
- 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.
Java NIO 通道不同於流的幾個點:
- 你可以讀也可以寫一個通道。流通常是單向的(讀或寫)。
- 通道可以異步讀寫。
- 通道總是從緩衝區讀或寫。
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:
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.
DatagramChannel可以通過UDP在網絡上讀寫數據
The SocketChannel
can read and write data over the network via TCP.
SocketChannel可以通過TCP在網絡上讀寫數據。
The ServerSocketChannel
allows you to listen for incoming TCP connections, like a web server does. For each incoming connection a SocketChannel
is created.
ServerSocketChannel
允許你監聽傳入的TCP連接,就像網絡服務器一樣。爲每個輸入連接創建一個SocketChannel
。
Basic Channel Example
Here is a basic example that uses a FileChannel
to read some data into a Buffer
:
上代碼,一個FileChannel的例子
public static void main(String[] args) throws IOException {
RandomAccessFile aFile = new RandomAccessFile("d://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.println((char)buf.get());
}
buf.clear();
bytesRead = inChannel.read(buf);
}
aFile.close();
}
我的文本內容:
abc efg
%6^&* () 90()
@! xyz ...
運行結果:
Read 44
a
b
c
e
f
g
%
6
^
&
*
(
)
9
0
ᆪ
ᄄ
ᆪ
ᄅ
@
ᆪ
ᄀ
x
y
z
.
.
.
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()的調用。首先,您讀取一個緩衝區。然後翻轉它。然後你讀出來。我將在下一篇關於緩衝區的文章中對此進行更詳細的討論。
這裏有一篇關於flip()方法的詳解,可以參考http://www.cnblogs.com/woshijpf/articles/3723364.html