美文网首页java技术基础java nioJava学习笔记
Java NIO 教程(十六) Java NIO Asynchr

Java NIO 教程(十六) Java NIO Asynchr

作者: 步积 | 来源:发表于2017-06-19 18:40 被阅读1028次

    原文地址

    目录

    在Java 7中,AsynchronousFileChannel被添加到Java NIO。AsynchronousFileChannel使读取数据,并异步地将数据写入文件成为可能。本教程将解释如何使用AsynchronousFileChannel

    创建一个AsynchronousFileChannel

    您可以通过它的静态方法open()创建一个AsynchronousFileChannel。下面是创建AsynchronousFileChannel的示例:

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

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

    第二个参数是一个或多个打开选项,它告诉AsynchronousFileChannel在底层文件上执行哪些操作。在本例中,我们使用了StandardOpenOption.READ选项。阅读意味着该文件将被打开以供阅读。

    读取数据

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

    通过Future阅读数据

    AsynchronousFileChannel读取数据的第一种方法是调用返回Future的read()方法。下面是如何调用这个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()之后,这个示例循环,直到返回的isDone()方法返回true。当然,这不是非常有效地使用CPU,但是您需要等到读取操作完成之后才会执行。

    读取操作完成后,数据读取到ByteBuffer中,然后进入一个字符串并打印到System.out中。

    通过一个CompletionHandler读取数据

    AsynchronousFileChannel读取数据的第二种方法是调用read()方法版本,该方法将一个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()方法。对于completed()方法的参数传递一个整数,它告诉我们读取了多少字节,以及传递给read()方法的“附件”。“附件”是read()方法的第三个参数。在本例中,它是ByteBuffer,数据也被读取。您可以自由选择要附加的对象。

    如果读取操作失败,则将调用CompletionHandlerfailed()方法。

    写数据

    就像阅读一样,您可以通过两种方式将数据写入一个AsynchronousFileChannel。写入数据的每一种方法都调用异步文件通道的write()方法之一。这两种方法都将在下面的部分中介绍。

    通过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);
    }
    

    通过一个CompletionHandler写入数据

    您还可以使用一个CompletionHandler将数据写入到AsynchronousFileChannel中,以告诉您何时完成写入,而不是Future。下面是一个将数据写入到AsynchronousFileChannel的示例,该通道有一个CompletionHandler:

    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 教程(十六) Java NIO Asynchr

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