Java NIO AsynchronousFileChannel
In Java 7 the AsynchronousFileChannel was added to Java NIO. The AsynchronousFileChannel makes it possible to read data from, and write data to files asynchronously. This tutorial will explain how to use the AsynchronousFileChannel.
Creating an AsynchronousFileChannel
You create an AsynchronousFileChannel via its static method open(). Here is an example of creating an AsynchronousFileChannel:
Path path = Paths.get("data/test.xml"); AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.READ);
The first parameter to the open() method is a Path instance pointing to the file the AsynchronousFileChannel is to be associated with.
The second parameter is one or more open options which tell the AsynchronousFileChannel what operations is to be performed on the underlying file. In this example we used the StandardOpenOption.READ which means that the file will be opened for reading.
Reading Data
You can read data from an AsynchronousFileChannel in two ways. Each way to read data call one of the read() methods of the AsynchronousFileChannel. Both methods of reading data will be covered in the following sections.
Reading Data Via a Future
The first way to read data from an AsynchronousFileChannel is to call the read() method that returns a Future. Here is how calling that read() method looks:
Future<Integer> operation = fileChannel.read(buffer, 0);
This version of the read() method takes ByteBuffer as first parameter. The data read from the AsynchronousFileChannel is read into this ByteBuffer. The second parameter is the byte position in the file to start reading from.
The read() method return immediately, even if the read operation has not finished. You can check the when the read operation is finished by calling the isDone() method of the Future instance returned by the read() method.
Here is a longer example showing how to use this version of the read() method:
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.READ); ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0; Future<Integer> operation = fileChannel.read(buffer, position); while(!operation.isDone()); buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println(new String(data));
buffer.clear();
This example creates an AsynchronousFileChannel and then creates a ByteBuffer which is passed to the read() method as parameter, along with a position of 0. After calling read() the example loops until the isDone() method of the returned Future returns true. Of course, this is not a very efficient use of the CPU - but somehow you need to wait until the read operation has completed.
Once the read operation has completed the data read into the ByteBuffer and then into a String and printed to System.out .
Reading Data Via a CompletionHandler
The second method of reading data from an AsynchronousFileChannel is to call the read() method version that takes a CompletionHandler as a parameter. Here is how you call this read() method:
fileChannel.read(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("result = " + 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) { }
});
Once the read operation finishes the CompletionHandler's completed() method will be called. As parameters to the completed() method are passed an Integer telling how many bytes were read, and the "attachment" which was passed to the read() method. The "attachment" is the third parameter to the read() method. In this case it was the ByteBuffer into which the data is also read. You can choose freely what object to attach.
If the read operation fails, the failed() method of the CompletionHandler will get called instead.
Writing Data
Just like with reading, you can write data to an AsynchronousFileChannel in two ways. Each way to write data call one of the write() methods of the AsynchronousFileChannel. Both methods of writing data will be covered in the following sections.
Writing Data Via a Future
The AsynchronousFileChannel also enables you to write data asynchronously. Here is a full Java AsynchronousFileChannel write example:
Path path = Paths.get("data/test-write.txt");
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.WRITE); ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0; buffer.put("test data".getBytes());
buffer.flip(); Future<Integer> operation = fileChannel.write(buffer, position);
buffer.clear(); while(!operation.isDone()); System.out.println("Write done");
First an AsynchronousFileChannel is opened in write mode. Then a ByteBuffer is created and some data written into it. Then the data in the ByteBuffer is written to the file. Finally the example checks the returned Future to see when the write operation has completed.
Note, that the file must already exist before this code will work. If the file does not exist the write() method will throw a java.nio.file.NoSuchFileException .
You can make sure that the file the Path points to exists with the following code:
if(!Files.exists(path)){
Files.createFile(path);
}
Writing Data Via a CompletionHandler
You can also write data to the AsynchronousFileChannel with a CompletionHandler to tell you when the write is complete instead of a Future. Here is an example of writing data to the AsynchronousFileChannel with a CompletionHandler:
Path path = Paths.get("data/test-write.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.WRITE); ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0; buffer.put("test data".getBytes());
buffer.flip(); fileChannel.write(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() { @Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("bytes written: " + result);
} @Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("Write failed");
exc.printStackTrace();
}
});
The CompletionHandler's completed() method will get called when the write operation completes. If the write fails for some reason, the failed() method will get called instead.
Notice how the ByteBuffer is used as attachment - the object which is passed on to the CompletionHandler's methods.
Ref:
http://tutorials.jenkov.com/java-nio/asynchronousfilechannel.html
Java NIO AsynchronousFileChannel的更多相关文章
- Java NIO学习系列七:Path、Files、AsynchronousFileChannel
相对于标准Java IO中通过File来指向文件和目录,Java NIO中提供了更丰富的类来支持对文件和目录的操作,不仅仅支持更多操作,还支持诸如异步读写等特性,本文我们就来学习一些Java NIO提 ...
- Java NIO 完全学习笔记(转)
本篇博客依照 Java NIO Tutorial翻译,算是学习 Java NIO 的一个读书笔记.建议大家可以去阅读原文,相信你肯定会受益良多. 1. Java NIO Tutorial Java N ...
- Java NIO 学习总结 学习手册
原文 并发编程网(翻译):http://ifeve.com/java-nio-all/ 源自 http://tutorials.jenkov.com/java-nio/index.html Java ...
- 海纳百川而来的一篇相当全面的Java NIO教程
目录 零.NIO包 一.Java NIO Channel通道 Channel的实现(Channel Implementations) Channel的基础示例(Basic Channel Exampl ...
- Java NIO文章列表(强烈推荐 转)
IO流学习总结 一 Java IO,硬骨头也能变软 二 java IO体系的学习总结 三 Java IO面试题 NIO与AIO学习总结 一 Java NIO 概览 二 Java NIO 之 Buffe ...
- Java NIO 学习笔记(六)----异步文件通道 AsynchronousFileChannel
目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...
- Java NIO、NIO.2学习笔记
相关学习资料 http://www.molotang.com/articles/903.html http://www.ibm.com/developerworks/cn/education/java ...
- Java NIO 学习
Java NIO提供了与标准IO不同的IO工作方式: Channels and Buffers(通道和缓冲区):标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(B ...
- Java NIO系列教程(八)JDK AIO编程
目录: Reactor(反应堆)和Proactor(前摄器) <I/O模型之三:两种高性能 I/O 设计模式 Reactor 和 Proactor> <[转]第8章 前摄器(Proa ...
随机推荐
- Ansible专题整理
Ansible 专题文章总览 Ansible小手册,仅供参考 文章如未明确说明实验环境,默认如下: OS:Centos 6.7 x86_64 Ansible: 2.1.2.0 Python: 2.6. ...
- 011.Zabbix的拓扑创建
一 Map简介 Map的作用是将各种设备用网络拓扑图的方式展示,在Zabbix中,拓扑的展示通过手动方式添加. 二 Map的添加 2.1 添加Map的背景图 #在添加Map之前可谓Map添加一个背景图 ...
- 前端页面重构技巧总结TIP【持续更新...】
本文均为项目实战经验,要求兼容至IE8,所以以下内容均为兼容代码,欢迎各位小伙伴批评指教.其实重构页面是一门学问,看似简单,却暗藏很多学问.实际项目中页面的重构有以下几点最基本需求: 1.需要使用合理 ...
- 浅析Entity FrameWork性能优化
浅析EF性能优化 1. 数据Load 延迟加载:当实体第一次读取时,相关数据没有加载:当第一次试图访问导航属性时,所需的导航数据自动加载,EF默认使用这种方式加载数据,尽量使用预先加载和显 ...
- codeforces_1092c
title: codeforces_1092c date: 2018-12-24 19:42:23 tags: acm 刷题 概述 一道有关字符串前缀后缀的题,,,自己迟早要坑在这字符串的题上,,,一 ...
- python删除执行路径下的空文件夹
def rm_emp_dir(path): """ 删除指定路径下的空文件夹 :param path: 指定路径 :type path: str :return: Non ...
- Chart.js Y轴数据以百分比展示
新手一枚,解决的问题喜欢记录,也许正好有人在网上迷茫的百度着.-0- 最近使用Chart.js做折线图的报表展示,直接显示整数啥的很好弄毕竟例子直接在哪里可以用,百分比就没办法了.百度慢慢汲取营养,虽 ...
- Lambda的分类(语句Lambda和表达式Lambda)
学习自 <C#本质论> Overview 在上一文中,我们简而又简的了解了一下,匿名方法和Lambda表达式,关于匿名方法这里暂且不表,本文我们来更加详细的了解一下Lambda表达式. 本 ...
- PHP 从基础开始 ——重要知识点笔记
PHP static 关键词 通常,当函数完成/执行后,会删除所有变量.不过,有时我需要不删除某个局部变量.实现这一点需要更进一步的工作. 要完成这一点,请在您首次声明变量时使用 static 关键词 ...
- Dos常用命令大全
dos命令进入文件夹 输入 D: 回车,进入D盘的根目录,然后输入dir 回车 可以查看根目录下的文件和文件夹, 输入 cd空格文件夹的名字(不区分大小写) 进入文件夹根目录下, 依次输入dir 查 ...