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

使用AsynchronousFileChannel类读取文件

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

502
使用AsynchronousFileChannel类读取文件
import java.io.IOException;

import java.nio.ByteBuffer;/**来 自 时代Java公众号 - nowjava.com**/

import java.nio.channels.AsynchronousFileChannel;

import java.nio.channels.CompletionHandler;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.util.EnumSet;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.ScheduledThreadPoolExecutor;

import java.util.concurrent.TimeUnit;


public class Main {

 

    public static void main(String args[]) {

        ExecutorService pool = new ScheduledThreadPoolExecutor(3);        

        try (AsynchronousFileChannel fileChannel =
        /**来自 
         N o  w  J a v a . c o m - 时  代  Java**/

                        AsynchronousFileChannel.open(Paths.get("/home/docs/items.txt"),

                        EnumSet.of(StandardOpenOption.READ), pool)) {

            System.out.println("Main Thread ID: " + Thread.currentThread().getId());


            CompletionHandler<Integer, ByteBuffer> handler =

                    new CompletionHandler<Integer, ByteBuffer>() {


                        @Override

                        public synchronized void completed(Integer result, ByteBuffer attachment) {

                            for (int i = 0; i < attachment.limit(); i++) {

                                System.out.print((char) attachment.get(i));

                            }

                            System.out.println("");

                            System.out.println("CompletionHandler Thread ID: "

                                    + Thread.currentThread().getId());

                            System.out.println("");

                        }


                        @Override

                        public void failed(Throwable e, ByteBuffer attachment) {

                            System.out.println("Failed");

                        }

                    };

            final int bufferCount = 5;

            ByteBuffer buffers[] = new ByteBuffer[bufferCount];

            for (int i = 0; i < bufferCount; i++) {

                buffers[i] = ByteBuffer.allocate(10);

                fileChannel.read(buffers[i], i * 10, buffers[i], handler);

            }

            pool.awaitTermination(1, TimeUnit.
展开阅读全文