Java - Asynchronous File I/O

Introduction

Java supports asynchronous file I/O.

java.nio.channels.AsynchronousFileChannel class represents an asynchronous file channel.

Multiple operations can be performed simultaneously on an asynchronous file channel.

The following code uses a CompletionHandler object to handle the results of an asynchronous write to a file.

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.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;

class Attachment {
  public Path path;
  public ByteBuffer buffer;
  public AsynchronousFileChannel asyncChannel;
}

class WriteHandler implements CompletionHandler<Integer, Attachment> {
  @Override/*w w  w  .  j  a va 2  s .c o m*/
  public void completed(Integer result, Attachment attach) {
    System.out.format("%s bytes written to %s%n", result,
        attach.path.toAbsolutePath());

    try {
      // Close the channel
      attach.asyncChannel.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void failed(Throwable e, Attachment attach) {
    System.out.format("Write operation on %s file failed."
        + " The error is:  %s%n", attach.path, e.getMessage());
    try {
      // Close the channel
      attach.asyncChannel.close();
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
}

public class Main {
  // An inner class to handle completion of the asynchronous write operation

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

    try {
      // Get an async channel
      AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, WRITE,
          CREATE);

      // Get a completion handler
      WriteHandler handler = new WriteHandler();
      // Get the data to write in a ByteBuffer
      ByteBuffer dataBuffer = getDataBuffer();

      // Prepare the attachment
      Attachment attach = new Attachment();
      attach.asyncChannel = afc;
      attach.buffer = dataBuffer;
      attach.path = path;

      // Perform the asynchronous write operation
      afc.write(dataBuffer, 0, attach, handler);

      try {
        // Let the thread sleep for five seconds,
        // to allow the asynchronous write is complete
        System.out.println("Sleeping for 5 seconds...");
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      System.out.println("Done...");
    } 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 Topics