Java NIO異步文件通道原理及用法解析
在Java 7,AsynchronousFileChannel 被添加到了Java NIO中。使用AsynchronousFileChannel可以實現(xiàn)異步地讀取和寫入文件數(shù)據(jù)。
創(chuàng)建一個AsynchronousFileChannel
我們可以使用AsynchronousFileChannel提供的靜態(tài)方法 open() 創(chuàng)建它。示例代碼如下:
Path path = Paths.get("data/test.xml");
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.READ);
第一個參數(shù)是一個 PATH 的對像實例,它指向了那個與 AsynchronousFileChannel 相關(guān)聯(lián)的文件。
第二個參數(shù)是一個或多個操作選項,它決定了 AsynchronousFileChannel 將對目標文件做何種操作。示例代碼中我們使用了 StandardOpenOption.READ ,它表明我們將要對目標文件進行讀操作。
讀取數(shù)據(jù)
AsynchronousFileChannel 提供了兩種讀取數(shù)據(jù)的方式,都是調(diào)用它本身的 read() 方法。下面將對兩種方式進行介紹。
使用Futrue讀取數(shù)據(jù)
第一種反式是調(diào)用 AsynchronousFileChannel 的 read() 方法,該方法反回一個 Future 類型的對象。
Future operation = fileChannelread(buffer, 0);
第一個參數(shù)是ByteBuffer,從 AsynchronousFileChannel 中讀取的數(shù)據(jù)先寫入這個 ByteBuffer 。
第二個參數(shù)表示從文件讀取數(shù)據(jù)的開始位置。
此 read() 方法會立即返回,即使整個讀的過程還沒有完全結(jié)束。我們可以通過operation.isDone()來檢查讀取是否完成。這里的 operation 是上面調(diào)用 read() 方法返回的 Future 類型的實例。下面是一段詳細的代碼示例:
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); ByteBuffer buffer = ByteBuffer.allocate(1024); long position = 0; Future<Integer> operation = fileChannel.read(buffer, position); while(!operation.isDone()); buffer.flip(); byte[] data = new byte[buffer.limit()]; buffer.get(data); System.out.println(new String(data)); buffer.clear();
上面的程序首先創(chuàng)建了一個 AsynchronousFileChannel 對象,然后調(diào)用它的read()方法返回一個Future。其中read()方法需要兩個參數(shù),一個是ByteBuffer,另一個是讀取文件的開始位置。然后通過循環(huán)調(diào)用isDone() 方法檢測讀取過程是否完成,完成后 isDone()方法將返回true。盡管這樣讓cpu空轉(zhuǎn)了一會,但是我們還是應(yīng)該等讀取操作完成后再進行后續(xù)的步驟。
一旦讀取完成,數(shù)據(jù)被存儲到ByteBuffer,然后將數(shù)據(jù)轉(zhuǎn)化為字符串既而輸出。
使用CompletionHandler讀取數(shù)據(jù)
第二種讀取數(shù)據(jù)的方式是調(diào)用AsynchronousFileChannel 的另一個重載 read() 方法,改方法需要一個CompletionHandler 作為參數(shù)。下面是代碼示例:
fileChannel.read(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer attachment) { System.out.println("result = " + result); attachment.flip(); byte[] data = new byte[attachment.limit()]; attachment.get(data); System.out.println(new String(data)); attachment.clear(); } @Override public void failed(Throwable exc, ByteBuffer attachment) { } });
一旦讀取操作完成,CompletionHandler的 complete() 方法將會被調(diào)用。它的第一個參數(shù)是個 Integer類型,表示讀取的字節(jié)數(shù)。第二個參數(shù) attachment 是 ByteBuffer 類型的,用來存儲讀取的數(shù)據(jù)。它其實就是由 read() 方法的第三個參數(shù)。當前示例中,我們選用 ByteBuffer 來存儲數(shù)據(jù),其實我們也可以選用其他的類型。
讀取失敗的時候,CompletionHandler的 failed()方法會被調(diào)用。
寫入數(shù)據(jù)
就像讀取一樣,我們同樣有兩種方式向 AsynchronousFileChannel 寫入數(shù)據(jù)。我們可以調(diào)用它的2個重載的 write() 方法。下面我們將分別加以介紹。
使用Future讀取數(shù)據(jù)
AsynchronousFileChannel也可以異步寫入數(shù)據(jù)。下面是一個完整的寫入示例:
AsynchronousFileChannel也可以異步寫入數(shù)據(jù)。下面是一個完整的寫入示例: Path path = Paths.get("data/test-write.txt"); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE); ByteBuffer buffer = ByteBuffer.allocate(1024); long position = 0; buffer.put("test data".getBytes()); buffer.flip(); Future<Integer> operation = fileChannel.write(buffer, position); buffer.clear(); while(!operation.isDone()); System.out.println("Write done");
首先實例化一個寫入模式的 AsynchronousFileChannel, 然后創(chuàng)建一個 ByteBuffer 并寫入一些數(shù)據(jù)。再然后將數(shù)據(jù)寫入文件。最后,檢查返回的 Future,看是否寫入完成。
注意,寫入目標文件要提前創(chuàng)建好,如果它不存在的話,writh() 方法會拋出一個 java.nio.file.NoSuchFileException。
我們可以用以下方式來解決這一問題:
if(!Files.exists(path)){
Files.createFile(path);
}
使用CompletionHandler寫入數(shù)據(jù)
我們也可以使用 CompletionHandler代替Future向AsynchronousFileChannel寫入數(shù)據(jù),這種方式可以更加直接的知道寫入過程是否完成。下面是示例程序:
Path path = Paths.get("data/test-write.txt"); if(!Files.exists(path)){ Files.createFile(path); } AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE); ByteBuffer buffer = ByteBuffer.allocate(1024); long position = 0; buffer.put("test data".getBytes()); buffer.flip(); fileChannel.write(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer attachment) { System.out.println("bytes written: " + result); } @Override public void failed(Throwable exc, ByteBuffer attachment) { System.out.println("Write failed"); exc.printStackTrace(); } });
當寫入程序完成時,CompletionHandler的completed()方法將會被調(diào)用,相反的如果寫入失敗則會調(diào)用failed()方法。
要留意CompletionHandler的方法的參數(shù) attachemnt是怎么使用的。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于maven install報錯原因揭秘:parent.relativePath指向錯誤的本地POM文件
在使用Maven進行項目構(gòu)建時,如果遇到'parent.relativePath'指向錯誤的本地POM文件的問題,可能會導(dǎo)致構(gòu)建失敗,這通常是由于父項目POM文件的相對路徑設(shè)置錯誤、本地POM文件與父項目POM文件版本或內(nèi)容不一致所致,解決方法包括檢查并修正父項目POM文件中的相對路徑設(shè)置2024-09-09jxl 導(dǎo)出數(shù)據(jù)到excel的實例講解
下面小編就為大家分享一篇jxl 導(dǎo)出數(shù)據(jù)到excel的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12Java實現(xiàn)的圖片高質(zhì)量縮放類定義與用法示例
這篇文章主要介紹了Java實現(xiàn)的圖片高質(zhì)量縮放類定義與用法,涉及java針對圖片的運算與轉(zhuǎn)換等相關(guān)操作技巧,需要的朋友可以參考下2017-11-11基于Java SSM實現(xiàn)Excel數(shù)據(jù)批量導(dǎo)入
這篇文章主要為大家詳細介紹了基于Java SSM如何實現(xiàn)excel數(shù)據(jù)批量導(dǎo)入,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11Java 把json對象轉(zhuǎn)成map鍵值對的方法
這篇文章主要介紹了java 把json對象中轉(zhuǎn)成map鍵值對的方法,本文的目的是把json串轉(zhuǎn)成map鍵值對存儲,而且只存儲葉節(jié)點的數(shù)據(jù) 。需要的朋友可以參考下2018-04-04