Channel(通道)是 Java NIO 中連接數據源與目標的核心抽象,它代表一個雙向的數據傳輸通路。與傳統 Stream 單向流不同,Channel 支持讀寫雙向操作,且能直接與作業系統底層 IO 服務交互,實現零拷貝、內存映射等高性能特性。
大多數 Channel 實現底層關聯文件描述符,提供跨平台的抽象層。Buffer(緩衝區)作為數據操作端點,Channel 負責數據在 Buffer 與 IO 服務間的搬運。
Channel API 以接口為核心設計,主要分為兩大類:
SocketChannel、ServerSocketChannel、DatagramChannel,對應 TCP/UDP 網絡 IO所有 Channel 基本雙向實現 ReadableByteChannel 與 WritableByteChannel,ByteChannel 只是語法糖簡化定義。
read(ByteBuffer) / write(ByteBuffer) 返回實際傳輸字節數,可能小於 Buffer 剩餘量(部分傳輸)。Buffer 的 position 會自動前移,支持循環調用直到 hasRemaining() 返回 false,實現大數據分塊傳輸。
public static void fileTransferByNormal() {
try (RandomAccessFile src = new RandomAccessFile("hello.txt", "rw");
RandomAccessFile dst = new RandomAccessFile("hehe.txt", "rw");
FileChannel in = src.getChannel();
FileChannel out = dst.getChannel()) {
ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
while (in.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
out.write(buffer);
}
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
非阻塞模式下調用線程不會休眠,請求立即完成或返回錯誤。SelectableChannel 結合 Selector 實現多路復用,是高並發網絡編程基石。
close() 無副作用ClosedByInterruptExceptionInterruptibleChannel 可異步關閉,喚醒阻塞線程拋出 AsynchronousCloseException掌握 Channel 的生命週期、線程交互語義對編寫健壯 NIO 程序至關重要。