---
title: "Java NIO Channel"
author: "clearity"
date: "2014-04-30T10:58:37Z"
tags: []
categories: ["互联网"]
slug: "java-nio-channel"
draft: false
lastmod: "2014-04-30T10:58:37Z"
id: 2057128
url: "https://clearity.iteye.com/blog/2057128"
---

Java中nio的通道和流有一些不同之处：

 1.通道可以同时支持读与写，而流只能是其中之一；

 2.通道支持异步读写；

 3.通道的读写都通过Buffer缓冲空间进行。

通道的读写流程如下：

![](http://dl2.iteye.com/upload/attachment/0096/6163/20ce735e-118d-3c74-a2d1-318260d676f3.png)  
 

通道的几种实现：

- FileChannel(服务于文件)
- DatagramChannel(服务于UDP数据报)
- SocketChannel(服务于TCP 的数据读写)
- ServerSocketChannel(服务于TCP 服务端，监听请求的TCP连接，为每个连接创建一个`SocketChannel` )

基本通道使用的例子

 

```
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();
```

 

注意buf.flip()的调用，首先它读取数据到缓冲空间，然后flip会从缓冲空间读出来。