对NIO 中channel的理解

Channel

NIO 中 一个 连接 就是 用 一个 Channel( 通道) 来 表示。 大家知道, 从更广泛 的 层面 来说, 一个 通道 可以 表示 一个 底层 的 文件 描述 符, 例如 硬件 设备、文件、 网络 连接 等。 然而, 远远 不止 如此, 除了 可以 对应 到底 层 文件 描述 符, Java NIO 的 通道 还可以 更加 细化。 例如, 对应 不同 的 网络 传输 协议 类型, 在 Java 中 都有 不同 的 NIO Channel( 通道) 实现。

Channel( 通道) 的 主要 类型

这里 不对 纷繁 复杂 的 Java NIO 通道 类型 进行 过多 的 描述, 仅仅 聚焦 于 介绍 其中 最为 重要的 四种 Channel( 通道) 实现: FileChannel、 SocketChannel、 ServerSocketChannel、 DatagramChannel。 对于 以上 四种 通道, 说明 如下:

  • (1) FileChannel 文件 通道, 用于 文件 的 数据 读写。
  • (2) SocketChannel 套 接 字 通道, 用于 Socket 套 接 字 TCP 连接 的 数据 读写。
  • (3) ServerSocketChannel 服务器 嵌套 字 通道( 或 服务器 监听 通道), 允许 我们 监听 TCP 连接 请求, 为 每个 监 听到 的 请求, 创建 一个 SocketChannel 套 接 字 通道。
  • (4) DatagramChannel 数据 报 通道, 用于 UDP 协议 的 数据 读写。 这个 四种 通道, 涵盖 了 文件 IO、 TCP 网络、 UDP IO 基础 IO。 下面 从 Channel( 通道) 的 获取、 读取、 写入、 关闭 四个 重要的 操作, 来 对 四种 通道 进行 简单 的 介绍。

FileChannel 文件 通道

FileChannel 是 专门 操作 文件 的 通道。 通过 FileChannel, 既可以 从 一个 文件 中 读取 数据, 也可以 将 数据 写入 到 文件 中。 特别 申明 一下, FileChannel 为 阻塞 模式, 不能 设置 为 非 阻塞 模式。 下面 分别 介绍: FileChannel 的 获取、 读取、 写入、 关闭 四个 操作。
通道

1. 获取 FileChannel 通道

可以 通过 文件 的 输入 流、 输出 流 获取 FileChannel 文件 通道, 示例 如下:

	FileInputStream fis = new FileInputStream(new File("C:\\Users\\asher\\Desktop\\新建文本文档 (2).txt"));
	//将inputStream转为fileChannel
        FileChannel inChannel = fis.getChannel();
	//申明byteBuffer,将channel中的数据写入byteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        inChannel.read(byteBuffer);
	//将写模式转为读模式
        byteBuffer.flip();
        byte[] inBytes = new byte[1024];
	//将byteBuffer写入byte数组
        byteBuffer.get(inBytes);
	//输出
        System.out.println(new String(inBytes));

也可以 通过 RandomAccessFile 文件 随机 访问 类, 获取 FileChannel 文件 通道:

// 创建 RandomAccessFile 随机 访问 对象
 RandomAccessFileaFile = new RandomAccessFile(" filename. txt"," rw"); 
//获取 文件 流的 通道 
FileChannelinChannel = aFile. getChannel();
# Netty 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×