Java - Use Future object to handle the results of an asynchronous read from a file.

Introduction

It uses the wait method, Future.get(), to wait for the asynchronous file I/O to complete.

Demo

import static java.nio.file.StandardOpenOption.READ;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Future;

public class Main {
  public static void main(String[] args) {
    Path path = Paths.get("data.txt");

    try (AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, READ)) {

      // Get a data buffer of the file size to read
      int fileSize = (int) afc.size();
      ByteBuffer dataBuffer = ByteBuffer.allocate(fileSize);

      // Perform the asynchronous read operation
      Future<Integer> result = afc.read(dataBuffer, 0);

      System.out.println("Waiting for reading to be finished...");
      // Let us wait until reading is finished
      int readBytes = result.get();

      System.out.format("%s bytes read from %s%n", readBytes, path);
      System.out.format("Read data is:%n");

      // Read the data from the buffer
      byte[] byteData = dataBuffer.array();
      Charset cs = Charset.forName("UTF-8");
      String data = new String(byteData, cs);

      System.out.println(data);//from   w w  w  . j a  v a2s. c o  m
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Result

Related Topic