集册 Java实例教程 将目标ByteBuffer的内容解码并显示到CompletionHandler的completed()方法中

将目标ByteBuffer的内容解码并显示到CompletionHandler的completed()方法中

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

477
将目标ByteBuffer的内容解码并显示到CompletionHandler的completed()方法中

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousFileChannel;
/**
 * nowjava - 时  代  Java 提 供 
**/

import java.nio.channels.CompletionHandler;

import java.nio.charset.Charset;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;


public class Main {

  static Thread current;

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

  public static void main(String[] args) {

    CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {

      String encoding = System.getProperty("file.encoding");/**来自 时 代 J a v a - nowjava.com**/

      @Override

      public void completed(Integer result, ByteBuffer attachment) {

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

        attachment.flip();

        System.out.print(Charset.forName(encoding).decode(attachment));

        attachment.clear();

        current.interrupt();

      }

      @Override

      public void failed(Throwable exc, ByteBuffer attachment) {

        System.out.println(attachment);

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

        current.interrupt();

      }

    };

    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel

        .open(path, StandardOpenOption.READ)) {

      current = Thread.currentThread();

      ByteBuffer buffer = ByteBuffer.allocate(100);

      asynchronousFileChannel.read(buff
展开阅读全文