Java Reference
In-Depth Information
String str = sb.toString();
Charset cs = Charset.forName("UTF-8");
ByteBuffer bb = ByteBuffer.wrap(str.getBytes(cs));
return bb;
}
}
Sleeping for 5 seconds...
228 bytes written to C:\book\javabook\rainbow.txt
Done...
Listing 10-22 demonstrates how to use a Future object to handle the results of an asynchronous write to a file. It
uses a try-with-resources clause to open an AsynchronousFileChannel . It uses a polling method ( Future.isDone()
method calls) to check if the I/O operation has completed. The program writes some text to a file named rainbow.txt
in the default directory. You may get a different output.
Listing 10-22. Using a Future Object to Handle the Result of an Asynchronous File Write
// AsyncFileWriteFuture.java
package com.jdojo.nio2;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.channels.AsynchronousFileChannel;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.nio.file.StandardOpenOption.CREATE;
public class AsyncFileWriteFuture {
public static void main(String[] args) {
Path path = Paths.get("rainbow.txt");
try (AsynchronousFileChannel afc =
AsynchronousFileChannel.open(path, WRITE, CREATE)) {
// Get the data to write in a ByteBuffer
ByteBuffer dataBuffer = AsyncFileWrite.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);
}
 
Search WWH ::




Custom Search