集册 Java实例教程 使用AsynchronousFileChannel读取文件和CompletionHandler

使用AsynchronousFileChannel读取文件和CompletionHandler

欢马劈雪     最近更新时间:2020-01-02 10:19:05

489
使用AsynchronousFileChannel读取文件和CompletionHandler

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousFileChannel;

import java.nio.channels.CompletionHandler;

import java.nio.file.Path;
/* 
*来 自
 N o  w  J a v a . c o m - 时  代  Java
*/

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;


public class Main {

  static Thread current;


  public static void main(String[] args) {

    ByteBuffer buffer = ByteBuffer.allocate(100);

    Path path = Paths.get("C:/folder1/", "test.txt");

    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel

        .open(path, StandardOpenOption.READ)) {

      current = Thread.currentThread();/**from 时 代 J a v a**/

      asynchronousFileChannel.read(buffer, 0, "Read operation status ...",

          new CompletionHandler<Integer, Object>() {

            @Override

            public void completed(Integer result, Object attachment) {

              System.out.println(attachment);

              System.out.print("Read bytes: " + result);

              current.interrupt();

            }


            @Override

            public void failed(Throwable exc, Object attachment) {

              System.out.println(attachment);

              System.out.println("Error:" + exc);

              current.interrupt();

            }

          });


      System
展开阅读全文