Java新AIO/NIO2:AsynchronousFileChannel以Future方式读

版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/87890510

Java新AIO/NIO2:AsynchronousFileChannel以Future方式读

假设现在有一个文件file.txt。里面有10个字符串文本:0123456789。为了完整说明BufferByte和AsynchronousFileChannel的读,故意设置ByteBuffer只有4字节。这样导致AsynchronousFileChannel一次性读取到缓冲器读不完,需要多次读写。

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;


public class Test {
	public static void main(String[] args) throws Exception {
		Path path = Paths.get("D:\\code\\file.txt");
		System.out.println(path);

		AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);

		ByteBuffer buffer = ByteBuffer.allocate(4);

		long size = fileChannel.size();

		int pos = 0, count = 0;
		while (pos < size) {
			count = read(fileChannel, buffer, pos);
			pos = pos + count;
		}
	}

	private static int read(AsynchronousFileChannel fileChannel, ByteBuffer buffer, int pos) throws Exception {
		Future<Integer> operation = fileChannel.read(buffer, pos);
		while (!operation.isDone()) {
			//不粗暴抢占CPU。
			Thread.sleep(1);
		}

		int count = 0;

		count = operation.get();
		System.out.println("读取数量:" + count);

		buffer.flip();
		System.out.println("数据内容:"+new String(buffer.array(), 0, count));
		buffer.clear();

		return count;
	}
}

输出:

D:\code\file.txt
读取数量:4
数据内容:0123
读取数量:4
数据内容:4567
读取数量:2
数据内容:89

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/87890510
今日推荐