Java Reference
In-Depth Information
// Get the data size in bytes to read
int fileSize = (int)afc.size();
ByteBuffer dataBuffer = ByteBuffer.allocate(fileSize);
// Prepare the attachment
Attachment attach = new Attachment();
attach.asyncChannel = afc;
attach.buffer = dataBuffer;
attach.path = path;
// Perform the asynchronous read operation
afc.read(dataBuffer, 0, attach, handler);
try {
// Let the thread sleep for five seconds,
// to allow the asynchronous read to complete
System.out.println("Sleeping for 5 seconds...");
Thread.sleep(5000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Done...");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Sleeping for 5 seconds...
228 bytes read from rainbow.txt
Read data is:
My heart leaps up when I behold
A Rainbow in the sky
So was it when my life began;
So is it now I am a man;
So be it when I shall grow old,
Or let me die!
The Child is father of the man;
And I could wish my days to be
Done...
Listing 10-24 demonstrates how to use a Future object to handle the results of an asynchronous read from a file.
It uses the wait method (a Future.get() method call) to wait for the asynchronous file I/O to complete. The program
reads the contents of a rainbow.txt file in the default directory. Change the path of this file if you want to read the
contents of a different file. You may get a different output.
Search WWH ::




Custom Search