NIO学习笔记(三)

                                         通道(Channel)

基本概念

通道(Channel):由 java.nio.channels 包定义的。 Channel 表示 IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过 Channel本身不能直接访问数据, Channel 只能与Buffer 进行交互。

  1. FileChannel:用于读取、写入、映射和操作文件的通道。
  2. DatagramChannel:通过 UDP 读写网络中的数据通道。
  3. SocketChannel:通过 TCP 读写网络中的数据。
  4. ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。

 

获取通道

获取通道的一种方式是对支持通道的对象调用getChannel() 方法。支持通道的类如下:

  1. FileInputStream
  2. FileOutputStream
  3. RandomAccessFile
  4. DatagramSocket
  5. Socket
  6. ServerSocket

获取通道的其他方式是使用 Files 类的静态方法 newByteChannel() 获取字节通道。或者通过通道的静态方法 open() 打开并返回指定通道。

数据传输

将 Buffer 中数据写入 Channel

//将Buffer中数据写入Channel中
int bytesWritten = inChannel.write(buf);

从 Channel 读取数据到 Buffer

//将Buffer中数据写入Channel中
int bytesWritten = inChannel.read(buf);

例一(利用通道完成文件复制(非直接缓冲区)):

long start = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
	fis = new FileInputStream("d:/jdk-6u45-windows-x64.exe");
	fos = new FileOutputStream("d:/jdk-6u45-windows-x642.exe");
	// 1.获取通道
	inChannel = fis.getChannel();
	outChannel = fos.getChannel();
	// 2.分配指定大小的缓冲区
	ByteBuffer buffer = ByteBuffer.allocate(1024);
	// 3.将通道中的数据写入缓冲区
	while (inChannel.read(buffer) != -1) {
		// 4.切换为读模式
		buffer.flip();
		// 5.将缓冲区中的数据写入到通道中
		outChannel.write(buffer);
		// 6.清空缓冲区
		buffer.clear();
	}
} catch (FileNotFoundException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
} finally {
	this.close(fis, fos, inChannel, outChannel);
}
long end = System.currentTimeMillis();
System.out.println("共耗时:" + (end - start) + "毫秒。");

共耗时:1463毫秒。

例二(使用直接缓冲区完成文件复制(内存映射文件)): 

long start = System.currentTimeMillis();
String as[] = {};
OpenOption aopenoption[] = { StandardOpenOption.READ,
			StandardOpenOption.WRITE, StandardOpenOption.CREATE };
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
	inChannel = FileChannel.open(
          Paths.get("d:/jdk-6u45-windows-x64.exe", as), aopenoption);
	outChannel = FileChannel.open(
		  Paths.get("d:/jdk-6u45-windows-x641.exe", as), aopenoption);

	// 内存映射文件
	MappedByteBuffer inMappedBuf = inChannel.map(MapMode.READ_ONLY, 0,
					inChannel.size());
	MappedByteBuffer outMappedBuf = outChannel.map(MapMode.READ_WRITE,
					0, inChannel.size());

	// 直接对缓冲区进行数据读写操作
	byte[] dst = new byte[inMappedBuf.limit()];
	inMappedBuf.get(dst);
	outMappedBuf.put(dst);
} catch (IOException e) {
	e.printStackTrace();
} finally {
	this.close(null, null, inChannel, outChannel);
}
long end = System.currentTimeMillis();
System.out.println("共耗时:" + (end - start) + "毫秒。");

 共耗时:126毫秒。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值