File Write and Future and AsynchronousFileChannel - Java File Path IO

Java examples for File Path IO:File Channel

Description

File Write and Future and 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;

public class Main {

  public static void main(String[] args) {
    ByteBuffer buffer = ByteBuffer.wrap("this is a test".getBytes());
    Path path = Paths.get("C:/folder1/", "story.txt");
    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
        .open(path, StandardOpenOption.WRITE)) {
      Future<Integer> result = asynchronousFileChannel.write(buffer, 100);
      while (!result.isDone()) {
        System.out.println("Do something else while writing ...");
      }//w  w w.j  av a 2  s  .co  m
      System.out.println("Written done: " + result.isDone());
      System.out.println("Bytes written: " + result.get());
    } catch (Exception ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials