Java 異步IO(2) 文件異步IO Callback

之前的文章寫的是利用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();
		}
	}


發佈了62 篇原創文章 · 獲贊 138 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章