1. 程式人生 > >Java粗淺認識-I/O(四)

Java粗淺認識-I/O(四)

AIO

什麼是AIO,既是非同步IO,這裡的非同步對照io第一篇裡面非同步IO流程圖,在請求資料和回傳資料兩個階段都是交給作業系統核心態非同步處理,無需使用者態阻塞等待,Java1.7中新增處理非同步IO的類,AsynchronousFileChannelAsynchronousServerSocketChannelAsynchronousSocketChannelAsynchronousChannelGroup(執行緒池管理),這裡需要注意一點,非同步IO只在Windows上真正實現。

1.AIO,檔案讀取

    private static void readFile() throws IOException, InterruptedException, ExecutionException {
        Path path = Paths.get("C:\\Users\\baopz\\Desktop\\圖片\\test\\1.txt");
        AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
        //16k
        ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 14);
        Future<Integer> future = asynchronousFileChannel.read(buffer, 0);
        System.out.println(future.get());
        asynchronousFileChannel.close();
    }

2.AIO,帶CompletionHandler處理

這裡使用了CompletionHandler的回撥處理機制,在任務處理完畢後,Handler會自行根據傳入的資料以及實現的邏輯進行結果處理,包括異常處理。

   public static void readFileWithCompletedHandler() throws IOException, InterruptedException {
        Path path = Paths.get("C:\\Users\\baopz\\Desktop\\圖片\\test\\1.gif");
        AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
        //16k
        ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 14);
        asynchronousFileChannel.read(buffer, 0, null, new CompletionHandler<Integer, Object>() {
            @Override
            public void completed(Integer result, Object attachment) {
                System.out.println("讀取檔案已經完成,讀取長度" + result);
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                System.out.println("讀取檔案錯誤");
            }
        });
        asynchronousFileChannel.close();
    }

3.AIO,檔案拷貝

  /**
     * 非同步檔案拷貝
     * @throws IOException
     */
    public static void copyFile() throws IOException {
        Path path = Paths.get("C:\\Users\\baopz\\Desktop\\圖片\\test\\1.gif");
        Path target = Paths.get("C:\\Users\\baopz\\Desktop\\圖片\\test\\2.gif");
        if (Files.notExists(target)) {
            Files.createFile(target);
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        AsynchronousFileChannel readChannel = AsynchronousFileChannel.open(path, Collections.singleton(StandardOpenOption.READ),executorService );
        AsynchronousFileChannel writeChannel = AsynchronousFileChannel.open(target, StandardOpenOption.WRITE);
        //16k
        final ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 14);
        readChannel.read(buffer, 0, writeChannel, new CompletionHandler<Integer, AsynchronousFileChannel>() {
            @Override
            public void completed(Integer result, AsynchronousFileChannel attachment) {
                buffer.flip();
                Future<Integer> future = attachment.write(buffer, 0);
                try {
                    System.out.println(future.get());
                    attachment.close();
                } catch (IOException | InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, AsynchronousFileChannel attachment) {
                System.out.println("異常情況" + exc.toString());
                try {
                    attachment.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        if(readChannel.isOpen()) {
            readChannel.close();
        }
        executorService.shutdown();
    }

4.AIO檔案網路通訊拷貝

1.server端

private static void server() throws IOException, InterruptedException, ExecutionException {
        AsynchronousChannelGroup group = AsynchronousChannelGroup.withCachedThreadPool(Executors.newCachedThreadPool(), 5);
        AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8888));
        System.out.println("繫結成功。");
        Future<AsynchronousSocketChannel> future = serverSocketChannel.accept();
        //阻塞接收連線
        AsynchronousSocketChannel asynchronousSocketChannel =  future.get();

        //16k
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1 << 14);
        asynchronousSocketChannel.read(byteBuffer);
        Path path = Paths.get("C:\\Users\\baopz\\Desktop\\圖片\\test\\4.gif");
        if (Files.notExists(path)) {
            try {
                Files.createFile(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            ExecutorService executorService1 = Executors.newCachedThreadPool();
            AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, Collections.singleton(StandardOpenOption.WRITE), executorService1);
            byteBuffer.flip();
            while (!asynchronousFileChannel.write(byteBuffer, 0).isDone()) {
                TimeUnit.MILLISECONDS.sleep(500);
            }
            asynchronousFileChannel.close();
            executorService1.shutdown();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        serverSocketChannel.close();
        if (!group.isShutdown()) {
            group.shutdown();
        }
    }

2.客戶端

private static void client() throws IOException, InterruptedException, ExecutionException {
        AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open();
        Future<Void> voidFuture = asynchronousSocketChannel.connect(new InetSocketAddress("127.0.0.1", 8888));
        //阻塞等待連線
        voidFuture.get();
        System.out.println("連線成功");
        Path path = Paths.get("C:\\Users\\baopz\\Desktop\\圖片\\test\\1.gif");
        //16k
        final ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 14);
        AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
        Future<Integer> integerFuture = asynchronousFileChannel.read(buffer, 0);
        int result = integerFuture.get();
        System.out.println(result);
        buffer.flip();
        Future<Integer> integerFuture1 = asynchronousSocketChannel.write(buffer);
        try {
            System.out.println("寫出去資料:" + integerFuture1.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        asynchronousSocketChannel.close();
    }

總結,到這裡Java I/O相關操作,介紹完畢,從Java 1.0開始的InputStrem和OutputStream,在Java 4中出現的Buffer、Channel、Selector,在Java 7出現的Path、Files、FilesSystems、AsynchronousFileChannel、AsynchronousServerSocketChannel等等都介紹完畢了,下一篇,記錄Java中網路通訊