File Read and Future Timeout with AsynchronousFileChannel - Java File Path IO

Java examples for File Path IO:File Channel

Description

File Read and Future Timeout with AsynchronousFileChannel

Demo Code

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
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);
      }/*from  www.j  av a 2  s. co m*/
    } catch (Exception ex) {
      if (ex instanceof TimeoutException) {
        if (result != null) {
          result.cancel(true);
        }
        System.out.println("cancelled:"+ result.isCancelled());
        System.out.println("Read bytes: " + bytesRead);
      } else {
        System.err.println(ex);
      }
    }
  }
}

Result


Related Tutorials