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的更多相关文章

  1. Java NIO学习系列七:Path、Files、AsynchronousFileChannel

    相对于标准Java IO中通过File来指向文件和目录,Java NIO中提供了更丰富的类来支持对文件和目录的操作,不仅仅支持更多操作,还支持诸如异步读写等特性,本文我们就来学习一些Java NIO提 ...

  2. Java NIO 完全学习笔记(转)

    本篇博客依照 Java NIO Tutorial翻译,算是学习 Java NIO 的一个读书笔记.建议大家可以去阅读原文,相信你肯定会受益良多. 1. Java NIO Tutorial Java N ...

  3. Java NIO 学习总结 学习手册

    原文 并发编程网(翻译):http://ifeve.com/java-nio-all/  源自 http://tutorials.jenkov.com/java-nio/index.html Java ...

  4. 海纳百川而来的一篇相当全面的Java NIO教程

    目录 零.NIO包 一.Java NIO Channel通道 Channel的实现(Channel Implementations) Channel的基础示例(Basic Channel Exampl ...

  5. Java NIO文章列表(强烈推荐 转)

    IO流学习总结 一 Java IO,硬骨头也能变软 二 java IO体系的学习总结 三 Java IO面试题 NIO与AIO学习总结 一 Java NIO 概览 二 Java NIO 之 Buffe ...

  6. Java NIO 学习笔记(六)----异步文件通道 AsynchronousFileChannel

    目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...

  7. Java NIO、NIO.2学习笔记

    相关学习资料 http://www.molotang.com/articles/903.html http://www.ibm.com/developerworks/cn/education/java ...

  8. Java NIO 学习

    Java NIO提供了与标准IO不同的IO工作方式: Channels and Buffers(通道和缓冲区):标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(B ...

  9. Java NIO系列教程(八)JDK AIO编程

    目录: Reactor(反应堆)和Proactor(前摄器) <I/O模型之三:两种高性能 I/O 设计模式 Reactor 和 Proactor> <[转]第8章 前摄器(Proa ...

随机推荐

  1. R语言编程艺术(5)R语言编程进阶

    本文对应<R语言编程艺术> 第14章:性能提升:速度和内存: 第15章:R与其他语言的接口: 第16章:R语言并行计算 ================================== ...

  2. CF 494 F. Abbreviation(动态规划)

    题目链接:[http://codeforces.com/contest/1003/problem/F] 题意:给出一个n字符串,这些字符串按顺序组成一个文本,字符串之间用空格隔开,文本的大小是字母+空 ...

  3. BZOJ4065 : [Cerc2012]Graphic Madness

    因为两棵树中间只有k条边,所以这些边一定要用到. 对于每棵树分别考虑: 如果一个点往下连着两个点,那么这个点往上的那条边一定不能用到. 如果一个点往下连着一个点,那么这个点往上的那条边一定不能用到. ...

  4. 获取设备IP地址

    腾讯的IP地址API接口地址:http://fw.qq.com/ipaddress返回的是数据格式为: 1 var IPData = new Array(“58.218.198.205″,”" ...

  5. 李善友《认知升级之第一性原理》--507张PPT全解!_搜狐科技_搜狐网

      http://www.sohu.com/a/151470602_733114

  6. WICED SDK 3.3.1

    7/20/2015 UPDATE: After installing the IDE you may not see all the APPs.  Press F5 in Eclipse to ref ...

  7. CSDN博客的积分计算方法和博客排名规律

    开通博客一段时间了,近期莫名其妙得获得"持之以恒"的勋章,看着日益增长的积分,既兴奋又好奇.本人对CSDN博客积分的计算方法非常疑惑,也不知当中怎么回事,好奇度娘一番,并结合CSD ...

  8. STM32F103 TIM3定时器初始化程序

    //TIM3 分频 #define TIM3_DIV1 (1-1) #define TIM3_DIV18 (18-1) #define TIM3_DIV72 (72-1) //************ ...

  9. 我是该学JAVA呢,还是学IOS开发呢?

    摘要: iOS就像Andriod一样,不是编程语言,而是操作系统.学iOS开发,其实学的是如何用Objective-C在苹果操作系统上进行各种应用程序的开发.就像学Andriod开发,其实是学如何用J ...

  10. C#轻量级高性能日志组件EasyLogger

    一.课程介绍 本次分享课程属于<C#高级编程实战技能开发宝典课程系列>中的第六部分,阿笨后续会计划将实际项目中的一些比较实用的关于C#高级编程的技巧分享出来给大家进行学习,不断的收集.整理 ...