Java新AIO/NIO2:AsynchronousFileChannel以Future方式读
  TEZNKK3IfmPf 2023年11月14日 22 0

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
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   19天前   43   0   0 java
  TEZNKK3IfmPf   2024年05月31日   54   0   0 java
TEZNKK3IfmPf