我正在使用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 :(得分: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完成。