File Read and Future and AsynchronousFileChannel - Java File Path IO

Java examples for File Path IO:File Channel

Description

File Read and Future and AsynchronousFileChannel

Demo Code

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.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

public class Main {
  public static void main(String[] args) {
    ByteBuffer buffer = ByteBuffer.allocate(100);
    String encoding = System.getProperty("file.encoding");
    Path path = Paths.get("C:/folder1/folder0/folder8", "story.txt");
    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
        .open(path, StandardOpenOption.READ)) {
      Future<Integer> result = asynchronousFileChannel.read(buffer, 0);
      while (!result.isDone()) {
        System.out.println("Do something else while reading ...");
      }//from w  ww.j a v a2s .co  m
      System.out.println("Read done: " + result.isDone());
      System.out.println("Bytes read: " + result.get());
    } catch (Exception ex) {
      System.err.println(ex);
    }
    buffer.flip();
    System.out.print(Charset.forName(encoding).decode(buffer));
    buffer.clear();
  }
}

Result


Related Tutorials