集册 Java实例教程 使用AsynchronousFileChannel读取文件和将来超时

使用AsynchronousFileChannel读取文件和将来超时

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

521
使用AsynchronousFileChannel读取文件和将来超时

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousFileChannel;/*时 代 J a v a*/

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.util.concurrent.Future;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.TimeoutException;


public class Main {

  public static void main(String[] args) {

    ByteBuffer buffer = ByteBuffer.allocate(100);

    int bytesRead = 0;

    Future<Integer> result = null;

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

    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel

        .open(path, StandardOpenOption.READ)) {

      result = asynchronousFileChannel.read(buffer, 0);

      bytesRead = result.get(1, TimeUnit.NANOSECONDS);

      if (result.isDone()) {

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

      }// 来自 n  o  w  j  a  v  a . c o m

    } catch (Exception ex) {

      if (ex instanceof TimeoutException) {

        if (result != null) {

         
展开阅读全文