之前的文章寫的是利用Future接口來做的異步IO,下面代碼是利用回調原理做的。
代碼如下:
public static void asynchronousFileIO_Callback()
{
Path path = Paths.get("resource/Stopword.txt");
try
{
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path);
ByteBuffer buffer = ByteBuffer.allocate(1000);
channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>()
{
@Override
public void completed(Integer result, ByteBuffer attachment)
{
System.out.println("Read " + result + " content is : " + new String(attachment.array()));
}
@Override
public void failed(Throwable exc, ByteBuffer attachment)
{
System.err.println(exc.getMessage());
}
});
int couter = 5;
while (couter > 0)
{
couter--;
System.out.println("do others.");
}
channel.close();
} catch (IOException e)
{
e.printStackTrace();
}
}