netty極簡教程(三): nio Channel意義以及FileChannel使用

上一章接單介紹了jdk nio中的容器Buffer的原理及使用: (netty極簡教程(二): nio Buffer的原理及使用)[https://www.jianshu.com/p/9a9feee6099e]
接下來我們繼續聊聊jdk nio中的Channel


示例源碼: https://github.com/jsbintask22/netty-learning

Channel介紹

在nio中,所有channel繼承自Channel(java.nio.channels.Channel)接口,它代表一個可以進行io操作的連接,可以是硬件設備,文件,網絡等等.


我們以FileChannel爲例,介紹下Channel的使用以及接口實現作用


  1. WritableChannel 可從ByteBuffer向Channel寫入數據 int write(ByteBuffer src)
  2. ReadableChannel 可從Channel向ByteBuffer讀取數據 int read(ByteBuffer dst)
  3. GatheringByteChannel 在WritableChannel的基礎上可寫入多個 ByteBuffer long write(ByteBuffer[] srcs)
  4. ScatteringByteChannel 在ReadableChannel的基礎上可向多個ByteBuffer讀取數據 long read(ByteBuffer[] dsts)
    其中ByteBuffer的作用及使用我們已經介紹,重點介紹下FileChannel的使用

FileChannel使用

寫入數據

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
  1. 通過FileChannel open方法獲取代表該文件連接的channel
  2. 從buffer中向channel寫入數據(寫入到對應的文件)

這裏值得注意的是,對於獲取channel的步驟,改寫法需要文件已經事先存在,如若文件不存在,可換另一種寫法:
fileChannel = new FileOutputStream("file_channel_example.txt");.getChannel(); 通過bio進行轉換

讀取數據

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
  1. 將channel的數據讀取都buffer
  2. 直接獲取buffer中的字節數據打印
  3. 利用buffer的position指針獲取有效數據然後打印

值得注意的是,這裏調用了buffer的flip方法,因爲上面的channel.read()方法已經移動了buffer中的指針

拷貝

有了上面的寫,讀 已經知道了拷貝的寫法,這裏我們假設分配的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());

總結

  1. channel的意義以及作用
  2. writable, readable, gatherting, Scattering 接口中新增的方法
  3. FileChannel的使用以及零拷貝
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章