Java - Use Future object to handle an asynchronous file operation

Introduction

The following code uses a Future object to handle an asynchronous file operation.

It uses a try-with-resources clause to open an AsynchronousFileChannel.

Then it uses Future.isDone() to check if the I/O operation has completed.

Demo

import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;

import java.io.IOException;
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.ExecutionException;
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,
        WRITE, CREATE)) {//from   w  w  w  . ja  va2s  .  c  om

      // Get the data to write in a ByteBuffer
      ByteBuffer dataBuffer = Main.getDataBuffer();

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

      // Keep polling to see if I/O has finished
      while (!result.isDone()) {
        try {
          // Let the thread sleep for 2 seconds
          // before the next polling
          System.out.println("Sleeping for 2 seconds...");
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }

      // I/O is complete
      try {
        int writtenBytes = result.get();
        System.out.format("%s bytes written to %s%n", writtenBytes,
            path.toAbsolutePath());
      } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static ByteBuffer getDataBuffer() {
    String lineSeparator = System.getProperty("line.separator");

    StringBuilder sb = new StringBuilder();
    sb.append("1");
    sb.append(lineSeparator);
    sb.append("2");
    sb.append(lineSeparator);
    sb.append(lineSeparator);
    sb.append("3");
    sb.append(lineSeparator);
    sb.append("4");
    sb.append(lineSeparator);
    sb.append("5");
    sb.append(lineSeparator);
    sb.append("6");
    sb.append(lineSeparator);
    sb.append(lineSeparator);
    sb.append("7");
    sb.append(lineSeparator);
    sb.append("8");
    String str = sb.toString();
    Charset cs = Charset.forName("UTF-8");
    ByteBuffer bb = ByteBuffer.wrap(str.getBytes(cs));

    return bb;
  }
}

Result

Related Topic