Using AsynchronousFileChannel to write ByteBuffer and return Future
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;
public class Test {
public static void main(String[] args) throws Exception {
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(
Paths.get("/asynchronous.txt"), StandardOpenOption.READ,
StandardOpenOption.WRITE, StandardOpenOption.CREATE);
Future<Integer> writeFuture1 = fileChannel.write(
ByteBuffer.wrap("Sample".getBytes()), 0);
Future<Integer> writeFuture2 = fileChannel.write(
ByteBuffer.wrap("Box".getBytes()), 0);
int result;
result = writeFuture1.get();
System.out.println("Sample write completed with " + result
+ " bytes written");
result = writeFuture2.get();
System.out.println("Box write completed with " + result + " bytes written");
}
}
Related examples in the same category