向Buffer中寫數據
寫數據到Buffer有兩種方式:
· 從Channel寫到Buffer。
· 通過Buffer的put()方法寫到Buffer里。
從Channel寫到Buffer的例子 :
int bytesRead = inChannel.read(buf); //read into buffer.通過put方法寫Buffer的例子:
buf.put(127);從Buffer中讀取數據
從Buffer中讀取數據有兩種方式:
· 從Buffer讀取數據到Channel。
· 使用get()方法從Buffer中讀取數據。從Buffer讀取數據到Channel的例子:
//read from buffer into channel. int bytesWritten = inChannel.write(buf);使用get()方法從Buffer中讀取數據的例子 :byte aByte = buf.get();
四、Selector - 選擇器
選擇器支持單個線程處理多個Channel,將多個Channel注冊到一個選擇器中,選擇器基于事件的方式處理;從選擇器獲取注冊Channel中關注的事件(如讀、寫)并進行數據處理,非常適用于多個數據量不大、讀寫不頻繁的通道,使用單個線程來處理;
五、NIO簡單(標準)的輸入/輸出
一個簡單(標準)的NIO輸入輸出一般包含如下步驟: 1. 從數據源獲取通道 2. 分配緩沖區 3. 切換緩存區為寫模式 4. 從通道讀取數據寫入緩沖區 5. 切換緩沖區為讀模式 6. 緩沖區數據寫入通道中 7. 關閉資源
實例代碼如下:
package com.denny.aio.test;import java.io.IOException;import java.io.RandomaccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class Test { public static void main(String[] args) throws IOException { RandomAccessFile formFile = new RandomAccessFile("src//a.txt", "rw"); RandomAccessFile toFile = new RandomAccessFile("src//b.txt", "rw"); //獲取channel FileChannel fromChannel = formFile.getChannel(); FileChannel toChannel = toFile.getChannel(); // 定義緩沖大小 int bufSize = 1024*4; // 定義緩沖 ByteBuffer byteBuffer = ByteBuffer.allocate(bufSize); int len = 0; // 將數據從源channel寫入到緩沖區 while( (len=fromChannel.read(byteBuffer)) !=-1 ){ //切換到讀模式 byteBuffer.flip(); //讀取緩沖區數據寫到目標channel toChannel.write(byteBuffer); // 清空緩沖 byteBuffer.clear(); } // 釋放資源 toChannel.close(); fromChannel.close(); }}
新聞熱點
疑難解答