在Java 7中,AsynchronousFileChannel已添加到Java NIO。 AsynchronousFileChannel使异步读写文件成为可能。接下来将说明如何使用AsynchronousFileChannel。
1.创建一个AsynchronousFileChannel
可以通过其静态方法open()创建一个AsynchronousFileChannel:
Path path = Paths.get("data/test.xml"); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
open()方法的第一个参数是一个Path实例,该实例指向与AsynchronousFileChannel关联的文件。
第二个参数是一个或多个打开的选项,它们告诉AsynchronousFileChannel对基础文件执行哪些操作。在此示例中,我们使用了StandardOpenOption.READ,这意味着将打开文件进行读取。
2.读取数据
可以通过两种方式从AsynchronousFileChannel读取数据。
3.通过Future读取数据
从AsynchronousFileChannel读取数据的第一种方法是调用read()方法,该方法返回Future。
Future<Integer> operation = fileChannel.read(buffer, 0);
此版本的read()方法将ByteBuffer作为第一个参数。从AsynchronousFil