美文网首页
AsynchronousFileChannel

AsynchronousFileChannel

作者: JiinYuu | 来源:发表于2019-01-04 14:02 被阅读0次

    AsynchronousFileChannel在Java7被加入了Java NIO。AsynchronousFileChannel让我们可以以异步的方式从文件读取或往文件写入数据。本教程会介绍怎么使用AsynchronousFileChannel

    Creating an AsynchronousFileChannel

    通过静态方法open()可以创建AsynchronousFileChannel实例。这有个例子:

    Path path = Paths.get("data/test.xml");
    
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
    

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

    第二个参数是一个或多个打开选项,它用来告诉AsynchronousFileChannel要对底层的文件执行什么操作。本例中,我们使用了StandardOpenOption.READ,意味着文件将被打开以供读取。

    Reading Data

    您可以通过两种方式从AsynchronousFileChannel读取数据。读取数据的每一种方法都调用AsynchronousFileChannelread()方法之一。这两种读取数据的方法将在下面的部分中介绍。

    Reading Data Via a Future

    第一种从AsynchronousFileChannel读取数据的方式是调用其返回值类型为Futureread()方法。就像下面这样:

    Future<Integer> operation = fielChannel.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,并同一个为0的位置一起作为参数传给了read()方法。在调用read()方法后,该例一直循环直到read()方法返回的Future对象的isDone()返回true为止。当然,这不是一种有效的CPU使用方式 - 但你总需要以某种方式等待读取操作完成。

    当读取操作完成后,数据就被读入了ByteBuffer,然后装入了String,然后打印。

    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) {
    
        }
    });
    

    当读取操作完成后,CompletionHandlercompleted()方法就会被调用。当传递给complete()方法的参数时,将传递一个整数,表示读取了多少字节,以及传递给read()方法的附件附件read()方法的第三个参数。本例中就是数据被读入的ByteBuffer。你可以选择附带任何对象。

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

    Writing Data

    就像读取数据一样,你有两种方式可以将数据写入AsynchronousFileChannel。写入数据的每一种方法都调用AsynchronousFileChannelwrite()方法之一。这两种写数据的方法将在下面的部分中介绍。

    Writing Data Via a 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,并向其中写入了一些数据。然后ByteBuffer中的数据被写入了文件。最后,例子通过检查返回的Future来看写入操作是否完成。

    注意,在代码工作之前,文件必须已经存在。如果文件不存在,write()方法会抛出一个java.nio.file.NoSuchFileException

    你可以通过以下代码来确保Path指向的文件存在:

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

    Writing Data Via a CompletionHandler

    你也可以用CompletionHandler代替Future来向AsynchronousFileChannel写入数据,以便在数据写入完成时告知你。下面是一个通过CompletionHandlerAsynchronousFileChannel写入数据的例子:

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

    当写入操作完成后,CompletionHandlercompleted()方法就会被调用。如果因为某些原因导致写入失败,failed()方法就会被调用。

    注意ByteBuffer是怎么作为附件使用的 - 传给CompletionHandler的方法的参数。

    发现貌似有人在看这个系列文章了,有必要说明下,这个Java NIO系列来源于jenkov.com,本文只是翻译,希望大家千万不要误会,本文不是原创。原文地址:Java NIO

    相关文章

      网友评论

          本文标题:AsynchronousFileChannel

          本文链接:https://www.haomeiwen.com/subject/rkmhrqtx.html