今天正學習AsychronousFileChannel的用法,相關API放在java.nio.channels.AsynchronousFileChannel,當然IO有關不外乎就是read跟write,今天先學習參考書目中的read的部分,說實在話還是不太懂,我的心得是這個API的好處應該是可以開多個執行緒,同時讀取同一個檔案的內容,讀取的內容彼此不會重疊,簡單範例如下,有時間的話會再編輯說明更清楚一點
首先要利用AsychronousFileChannel中的方法將檔案讀入,實作CompletionHandler代表每個執行緒所要做的工作,以這個case的話,是讀指定大小的byte,並顯示讀了哪些內容,利用ByteBuffer儲存各執行緒所讀入的byte,最後在全部顯示。
package mynio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.*;
import java.util.EnumSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
*
* @author joombuopre
*/
public class MyNIO {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
Path seo=Paths.get("H:\\1_2.txt");
ExecutorService pool= new ScheduledThreadPoolExecutor(10);
try(AsynchronousFileChannel fc=AsynchronousFileChannel.open(seo, EnumSet.of(StandardOpenOption.READ), pool)){
CompletionHandler<Integer, ByteBuffer> handler= new CompletionHandler<Integer, ByteBuffer>(){
@Override
public synchronized void completed(Integer result, ByteBuffer attachment) {
// TODO Auto-generated method stub
for(int i=0; i< attachment.limit();i++){
System.out.print((char)attachment.get(i));
}
System.out.println("");
System.out.println("CompletionThread:"+Thread.currentThread().getId());
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
// TODO Auto-generated method stub
exc.printStackTrace();
}
};
final int bufferCount =5;
ByteBuffer buffers[]=new ByteBuffer[bufferCount];
for(int i=0;i<bufferCount;i++){
buffers[i]=ByteBuffer.allocate(1000);
fc.read(buffers[i], i*10, buffers[i], handler);
}
try {
pool.awaitTermination(0, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Byte Buffers");
for(ByteBuffer byteBuffer:buffers){
for(int i=0;i<byteBuffer.limit();i++){
System.out.print((char)byteBuffer.get(i));
}
System.out.println("");
}
}
}
}