上一章接單介紹了jdk nio中的容器Buffer的原理及使用: (netty極簡教程(二): nio Buffer的原理及使用)[http://www.itdecent.cn/p/9a9feee6099e],
接下來我們繼續(xù)聊聊jdk nio中的Channel
示例源碼: https://github.com/jsbintask22/netty-learning
Channel介紹
在nio中,所有channel繼承自Channel(java.nio.channels.Channel)接口,它代表一個可以進(jìn)行io操作的連接,可以是硬件設(shè)備,文件,網(wǎng)絡(luò)等等.
我們以FileChannel為例,介紹下Channel的使用以及接口實現(xiàn)作用

image
- WritableChannel 可從ByteBuffer向Channel寫入數(shù)據(jù)
int write(ByteBuffer src) - ReadableChannel 可從Channel向ByteBuffer讀取數(shù)據(jù)
int read(ByteBuffer dst) - GatheringByteChannel 在WritableChannel的基礎(chǔ)上可寫入多個 ByteBuffer
long write(ByteBuffer[] srcs) - ScatteringByteChannel 在ReadableChannel的基礎(chǔ)上可向多個ByteBuffer讀取數(shù)據(jù)
long read(ByteBuffer[] dsts)
其中ByteBuffer的作用及使用我們已經(jīng)介紹,重點介紹下FileChannel的使用
FileChannel使用
寫入數(shù)據(jù)
FileChannel fileChannel = FileChannel.open(Paths.get("", "file_channel_example.txt"), // 1
StandardOpenOption.WRITE,
StandardOpenOption.READ);
String src = "hello from jsbintask.cn zh中文\n...test";
// write
ByteBuffer writeBuffer = ByteBuffer.wrap(src.getBytes(StandardCharsets.UTF_8));
fileChannel.write(writeBuffer); // 2
- 通過FileChannel open方法獲取代表該文件連接的channel
- 從buffer中向channel寫入數(shù)據(jù)(寫入到對應(yīng)的文件)
這里值得注意的是,對于獲取channel的步驟,改寫法需要文件已經(jīng)事先存在,如若文件不存在,可換另一種寫法:
fileChannel = new FileOutputStream("file_channel_example.txt");.getChannel(); 通過bio進(jìn)行轉(zhuǎn)換
讀取數(shù)據(jù)
FileInputStream fis = new FileInputStream("file_channel_example.txt");
FileChannel fileChannel = fis.getChannel();
// read
ByteBuffer readBuffer = ByteBuffer.allocate(100);
int length = fileChannel.read(readBuffer); // 1
// method 1
System.out.println(new String(readBuffer.array())); // 2
// method 2
readBuffer.flip();
byte[] data = new byte[length];
int index = 0;
while (readBuffer.hasRemaining()) {
data[index++] = readBuffer.get();
}
System.out.println(new String(data)); // 3
- 將channel的數(shù)據(jù)讀取都buffer
- 直接獲取buffer中的字節(jié)數(shù)據(jù)打印
- 利用buffer的position指針獲取有效數(shù)據(jù)然后打印
值得注意的是,這里調(diào)用了buffer的flip方法,因為上面的channel.read()方法已經(jīng)移動了buffer中的指針
拷貝
有了上面的寫,讀 已經(jīng)知道了拷貝的寫法,這里我們假設(shè)分配的buffer很小,則需要分多次才能copy完成
// copy: file_1.txt => file_2.txt
FileChannel fileChannel = new FileInputStream("file_channel_example.txt").getChannel();
// write
FileChannel writeChannel = new FileOutputStream("file_channel_example_copy.txt").getChannel();
// 只分配一塊很小的 緩存 分多次讀
ByteBuffer readBuffer = ByteBuffer.allocate(3); // 1
int len = -1;
while ((len = fileChannel.read(readBuffer)) != -1) { // 2
readBuffer.flip(); // 3
writeChannel.write(readBuffer);
readBuffer.clear(); // 4
}
零拷貝
FileChannel有一個省去中間buffer的方法,即我們所謂的零拷貝
readChannel.transferTo(0, fis.available(), writeChannel);
writeChannel.transferFrom(readChannel, fis.available(), fis.available());
總結(jié)
- channel的意義以及作用
- writable, readable, gatherting, Scattering 接口中新增的方法
- FileChannel的使用以及零拷貝