02. Java NIO Channel

 

Java NIO的通道(Channel)类似流,但又有些不同:

1. 既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。

2. 通道可以异步地读写。通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。

    正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。如下图所示:



 

Channel的实现

 

这些是Java NIO中最重要的通道的实现:

FileChannel 从文件中读写数据。

DatagramChannel 能通过UDP读写网络中的数据。

SocketChannel 能通过TCP读写网络中的数据。

ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。

 

package com.ihuning.javase.demo.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {

	private static final String FILE_PATH = "src/com/ihuning/javase/demo/nio/demo.txt";
	
	public static void display() throws Exception
	{
		RandomAccessFile file = new RandomAccessFile(FILE_PATH,"rw");
		FileChannel channel = file.getChannel();
		
		int readByte = 0;
		ByteBuffer buf = ByteBuffer.allocate(10);
		
		while((readByte = channel.read(buf)) != -1)
		{
			buf.flip(); //prepare for reading
			for(int i = 0; i < readByte; i++)
			{
				System.out.print((char)buf.get(i));
			}
		}
		file.close();
	}
	
	public static void show() throws Exception {
		
		RandomAccessFile raf = new RandomAccessFile(FILE_PATH, "rw");
		FileChannel fileChannel = raf.getChannel();
		ByteBuffer buf = ByteBuffer.allocate(10);

		int readByte = 0;
		while ((readByte = fileChannel.read(buf)) != -1) {
			buf.flip();//prepare for reading
			while (buf.hasRemaining()) {
				System.out.print((char) buf.get());
			}
			buf.clear();//prepare for writing
		}
		raf.close();
	}

	public static void main(String[] args) throws Exception{

		FileChannelDemo.show();
		FileChannelDemo.display();
	}
}

 

注意 buf.flip() 的调用,首先读取数据到Buffer,然后反转Buffer,接着再从Buffer中读取数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值