Java NIO AsynchronousFileChannel

AsynchronousFileChannel

在Java 7中,Java NIO中添加了AsynchronousFileChannel,也就是异步地将数据写入文件。

创建AsynchronousFileChannel

通过静态方法open()创建

Path path = Paths.get("d:\\qrxqrx\\01.txt");
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path,StandardOpenOption.READ);

通过Future读取数据

可以通过两种方式从AsynchronousFileChannel读取数据。第一种方式是调用返回Future的read()方法。

Path path = Paths.get("d:\\qrxqrx\\01.txt");
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path,StandardOpenOption.READ);
ByteBuffer buf = ByteBuffer.allocate(1024);
long position = 0;
Future<Integer> operation = fileChannel.read(buf,position);
while (!operation.isDone());
buf.flip();
byte[] data = new byte[buf.limit()];
buf.get(data);
System.out.println(new String(data));
buf.clear();

通过CompletionHandler读取数据

第二种方法是调用read()方法,该方法将一个CompletionHandler作为参数。

Path path = Paths.get("d:\\qrxqrx\\01.txt");
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path,StandardOpenOption.READ);
ByteBuffer buf = ByteBuffer.allocate(1024);
long position = 0;
fileChannel.read(buf,position,buf,new CompletionHandler<Integer,ByteBuffer>() {
	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		System.out.println(result);
		attachment.flip();
		byte[] data = new byte[attachment.limit()];
		attachment.get(data);
		System.out.println(new String(data));
		attachment.clear();
	}
	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
	}
});

通过Future写数据

和读取数据一样,可以通过两种方式将数据写入到一个AsynchronousFileChannel。

Path path = Paths.get("d:\\qrxqrx\\01.txt");
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path,StandardOpenOption.WRITE);
ByteBuffer buf = ByteBuffer.allocate(1024);
long position = 0;
buf.put("abc".getBytes());
buf.flip();
Future<Integer> operation = fileChannel.write(buf,position);
while (!operation.isDone());
System.out.println("write over!");
buf.clear();

通过CompletionHandler写数据

Path path = Paths.get("d:\\qrxqrx\\01.txt");
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path,StandardOpenOption.READ);
ByteBuffer buf = ByteBuffer.allocate(1024);
long position = 0;
buf.put("abc".getBytes());
buf.flip();
fileChannel.write(buf,position,buf,new CompletionHandler<Integer,ByteBuffer>() {
	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		System.out.println(result);
		System.out.println("write over !");
		attachment.clear();
	}
	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
	}
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值