Java Reference
In-Depth Information
You can use an object of the MyHandler class to handle the completion of an asynchronous file I/O operation.
The following snippet of code uses a MyHandler instance as a completion handler for an asynchronous write
operation. The completed() or failed() method of the MyHandler instance will be called depending on the result of
the I/O operation.
// Get a completion handler
MyHandler handler = new MyHandler();
// Get the data to write in a ByteBuffer
ByteBuffer dataBuffer = get a data buffer;
// 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);
the ByteBuffer that is used to read or write in an asynchronous file operation should not be used by the application
between the time it is used in an asynchronous file I/O request and the time the request is completed. Otherwise, it will
have an unpredictable result. You can close an AsynchronousFileChannel using its close() method. all pending
operations are completed with a java.nio.channels.AsynchronousCloseException when its close() method is called.
Tip
Listing 10-21 demonstrates how to use a CompletionHandler object to handle the results of an asynchronous
write to a file. After submitting the request for the asynchronous write on a file, the main thread sleeps for 5 seconds to
give the asynchronous operation time to finish. In a real-world application, after submitting an asynchronous file I/O
request, you would continue performing other tasks. The program writes some text to a rainbow.txt file in the default
directory. You may get a different output.
Listing 10-21. Using a CompletionHandler Object to Handle the Result of an Asynchronous File Write
// AsyncFileWrite.java
package com.jdojo.nio2;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.channels.CompletionHandler;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.nio.file.StandardOpenOption.CREATE;
 
 
Search WWH ::




Custom Search