Java NIO学习教程(九)

17.Java NIO AsynchronousFileChannel

在Java 7中,AsynchronousFileChannel已添加到Java NIO中。AsynchronousFileChannel可以异步读取数据和将数据写入文件。本教程将介绍如何使用AsynchronousFileChannel。

Creating an AsynchronousFileChannel
你可以通过静态方法open( )创建AsynchronousFileChannel。以下是创建AsynchronousFileChannel示例:

Path path = Paths.get("data/test.xml");

AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path,StandardOpenOption.READ);

open( )方法的第一个参数是指向AsynchronousFileChannel要与之关联的文件的Path实例。

第二个参数是一个或多个打开选项,用于指示AsynchronousFileChannel要对基础文件执行哪些操作。在这个例子中,我们使用了StandardOpenOption.READ 这意味着打开文件进行读取。

Reading Data
你可以通过两种方式从AsynchronousFileChannel中读取数据。每种读取数据的 方法都会调用AsynchronousFileChannel中的read( )方法。以下各节将介绍这两种读取数据的方法。

Reading Data Via a Future
从AsynchronousFileChannel读取数据的第一种方法是调用read( )方法,该方法返回一个Future。以下是调用该read( )方法的方式:

Future<Integer> operation = fileChannel.read(buffer, 0);

此版本的read( )方法ByteBuffer作为第一个参数。从AsynchronousFileChannel读取的数据被读入ByteBuffer。第二个参数是文件中要开始读取的字节位置。

即使读取操作尚未完成, read( )方法也会立即返回。你可以通过调用read( )方法返回的Future实例的isDone( )方法来检查读取操作何时完成。

这是一个更长的示例,显示如何使用此版本的read()方法:

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();

此示例创建一个AsynchronousFileChannel,然后创建一个ByteBuffer,它作为参数传递给read( )方法,并且位置为0。在调用read( ) 之后,示例循环,直到返回的Future的isDone( )方法返回true。当然,这不是一个非常有效的CPU使用——但不知何故,你需要等到读操作完成。

一旦读取操作完成,数据将读入ByteBuffer,然后再读入String并打印到System.out。

Reading Data Via a CompletionHandler
从AsynchronousFileChannel读取数据的第二种方法是调用CompletionHandler作为参数的方法版本。以下是你调用此read( )方法的方法:

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的completed()方法。作为completed( )方法的参数,传递一个整数,告诉读取了多少字节,以及传递给read()方法的“attachment”。“attachment”是read( )方法的第三个参数。在本例中,它是一个字节缓冲区,数据也被读取到这个字节缓冲区中。你可以自由选择要附加的对象。

如果读取操作失败,则会调用CompletionHandler的failed( )方法。

Writing Data
就像读取数据一样,你可以通过两种方式将数据写入AsynchronousFileChannel。每种写入数据的方式都调用AsynchronousFileChannel中的write( )方法。以下各节将介绍这两种写入数据的方法。

Writing Data Via a Future
AsynchronousFileChannel还允许你异步写入数据。这是一个完整的Java AsynchronousFileChannel编写示例:

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以写入模式打开。然后创建一个ByteBuffer并写入一些数据。然后将ByteBuffer中的数据写入文件。最后,该示例检查返回Future以查看写入操作何时完成。

请注意,在此代码起作用之前,该文件必须已存在。如果该文件不存在,该write() 方法将抛出一个java.nio.file.NoSuchFileException。

你可以使用以下代码确保Path指向的文件存在:

if(!Files.exists(path)){
    Files.createFile(path);
}

Writing Data Via a CompletionHandler
你还可以使用CompletionHandler将数据
写入AsynchronousFileChannela,以告知你何时完成写入,而不是返回一个Future。以下是使用CompletionHandler将数据写入AsynchronousFileChannel的示例:

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( )方法。如果由于某种原因写入失败,则会调用failed( )方法。

注意,ByteBuffer是如何用作附件的——传递给CompletionHandler方法的对象。

【上篇】Java NIO学习教程(八)==>点击

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值