Java NIO异步文件通道原理及用法解析

2022-07-30,,,,

在java 7,asynchronousfilechannel 被添加到了java nio中。使用asynchronousfilechannel可以实现异步地读取和写入文件数据。

创建一个asynchronousfilechannel

我们可以使用asynchronousfilechannel提供的静态方法 open() 创建它。示例代码如下:

path path = paths.get("data/test.xml");
asynchronousfilechannel filechannel =
asynchronousfilechannel.open(path, standardopenoption.read);

第一个参数是一个 path 的对像实例,它指向了那个与 asynchronousfilechannel 相关联的文件。

第二个参数是一个或多个操作选项,它决定了 asynchronousfilechannel 将对目标文件做何种操作。示例代码中我们使用了 standardopenoption.read ,它表明我们将要对目标文件进行读操作。

读取数据

asynchronousfilechannel 提供了两种读取数据的方式,都是调用它本身的 read() 方法。下面将对两种方式进行介绍。

使用futrue读取数据

第一种反式是调用 asynchronousfilechannel 的 read() 方法,该方法反回一个 future 类型的对象。

future operation = filechannelread(buffer, 0);

第一个参数是bytebuffer,从 asynchronousfilechannel 中读取的数据先写入这个 bytebuffer 。

第二个参数表示从文件读取数据的开始位置。

此 read() 方法会立即返回,即使整个读的过程还没有完全结束。我们可以通过operation.isdone()来检查读取是否完成。这里的 operation 是上面调用 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();

上面的程序首先创建了一个 asynchronousfilechannel 对象,然后调用它的read()方法返回一个future。其中read()方法需要两个参数,一个是bytebuffer,另一个是读取文件的开始位置。然后通过循环调用isdone() 方法检测读取过程是否完成,完成后 isdone()方法将返回true。尽管这样让cpu空转了一会,但是我们还是应该等读取操作完成后再进行后续的步骤。

一旦读取完成,数据被存储到bytebuffer,然后将数据转化为字符串既而输出。

使用completionhandler读取数据

第二种读取数据的方式是调用asynchronousfilechannel 的另一个重载 read() 方法,改方法需要一个completionhandler 作为参数。下面是代码示例:

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() 方法将会被调用。它的第一个参数是个 integer类型,表示读取的字节数。第二个参数 attachment 是 bytebuffer 类型的,用来存储读取的数据。它其实就是由 read() 方法的第三个参数。当前示例中,我们选用 bytebuffer 来存储数据,其实我们也可以选用其他的类型。

读取失败的时候,completionhandler的 failed()方法会被调用。

写入数据

就像读取一样,我们同样有两种方式向 asynchronousfilechannel 写入数据。我们可以调用它的2个重载的 write() 方法。下面我们将分别加以介绍。

使用future读取数据

asynchronousfilechannel也可以异步写入数据。下面是一个完整的写入示例:

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 并写入一些数据。再然后将数据写入文件。最后,检查返回的 future,看是否写入完成。

注意,写入目标文件要提前创建好,如果它不存在的话,writh() 方法会抛出一个 java.nio.file.nosuchfileexception。

我们可以用以下方式来解决这一问题:

if(!files.exists(path)){
files.createfile(path);
}

使用completionhandler写入数据

我们也可以使用 completionhandler代替future向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()方法。

要留意completionhandler的方法的参数 attachemnt是怎么使用的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《Java NIO异步文件通道原理及用法解析.doc》

下载本文的Word格式文档,以方便收藏与打印。