Java NIO Channel

源自:http://tutorials.jenkov.com/java-nio/channels.html

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值