2016-12-12 9 views
0

次のように私はRandomFileAccess、のFileChannelとのByteBufferを使用してファイルを読んでいます:ファイルチャネルを使用して将来のデータを読み取る方法は?

RandomAccessFile myFile = new RandomAccessFile("/Users/****/Documents/a.txt", "rw"); 
FileChannel myInChannel = myFile.getChannel(); 

ByteBuffer bb = ByteBuffer.allocate(48); 

int bytesRead = myInChannel.read(bb); 
while (bytesRead != -1) { 
    // do something 
} 
myFile.close(); 

すべてこのコードが正常に動作しています。 しかし、私はFutureを使用してデータを読み取ることができる方法はありますか?

+0

「Future」を介して結果を消費するスレッドから読み込みを開始するスレッドをどのように切り離すかを尋ねていますか?私は 'FileChannel'sがフードの下でブロッキング同期呼び出しをしている可能性が高いので頼みます。そのため、Futureを使用すると非同期操作の方法で何も買われません。 – Gili

+0

FileChannelを介して行うことができるかどうかわかりません。もしそうでなければ、その代案は何ですか? – KayV

+0

申し訳ありませんが、何をしようとしていますか?なぜ未来が必要なのですか?あなたは 'FileChannel'を使って非同期に読み込もうとしていますか?上記の更新されたコメントを読んでください。 – Gili

答えて

1

私は、次のコードを試みたが、それがためにうまく働いた:

try(AsynchronousFileChannel afileChannel = AsynchronousFileChannel.open(Paths.get("/Users/***/Documents/myFile.txt"), StandardOpenOption.READ)) { 

     ByteBuffer buffer = ByteBuffer.allocate(1024); 
     long position = 0; 

     Future<Integer> operation = afileChannel.read(buffer, position); 

     while(!operation.isDone()){ 
      //do something 
     } 

     buffer.flip(); 
     byte[] data = new byte[buffer.limit()]; 
     buffer.get(data); 
     System.out.println(new String(data)); 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

が、これはAsynchronousFileChannel経由ではなく、のFileChannelを介して行うことができることを知りました。

+0

はい。それはそれを行うよ:) – Gili

+0

@Giliは検証のためにありがとう。 – KayV

関連する問題