Java NIO AsynchronousFileChannel
2016-03-12 23:25
615 查看
Creating an AsynchronousFileChannel
Reading Data
Reading Data Via a Future
Reading Data Via a CompletionHandler
Writing Data
Writing Data Via a Future
Writing Data Via a CompletionHandler
In Java 7 the
You create an
The first parameter to the
to be associated with.
The second parameter is one or more open options which tell the
opened for reading.
You can read data from an
The first way to read data from an
This version of the
reading from.
The
Here is a longer example showing how to use this version of the
This example creates an
of the returned
Once the read operation has completed the data read into the
The second method of reading data from an
Once the read operation finishes the
which was passed to the
If the read operation fails, the
Just like with reading, you can write data to an
in the following sections.
The
First an
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
You can make sure that the file the
You can also write data to the
a
The
Notice how the
Reading Data
Reading Data Via a Future
Reading Data Via a CompletionHandler
Writing Data
Writing Data Via a Future
Writing Data Via a CompletionHandler
Jakob Jenkov Last update: 2015-05-07 |
AsynchronousFileChannelwas added to Java NIO. The
AsynchronousFileChannelmakes 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 AsynchronousFileChannelvia 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
AsynchronousFileChannelis
to be associated with.
The second parameter is one or more open options which tell the
AsynchronousFileChannelwhat operations is to be performed on the underlying file. In this example we used the
StandardOpenOption.READwhich means that the file will be
opened for reading.
Reading Data
You can read data from an AsynchronousFileChannelin 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 AsynchronousFileChannelis 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
ByteBufferas first parameter. The data read from the
AsynchronousFileChannelis 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
Futureinstance 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
AsynchronousFileChanneland then creates a
ByteBufferwhich 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
Futurereturns 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
ByteBufferand then into a String and printed to
System.out.
Reading Data Via a CompletionHandler
The second method of reading data from an AsynchronousFileChannelis to call the
read()method version that takes a
CompletionHandleras 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
Integertelling 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
ByteBufferinto which the data is also read. You can choose freely what object to attach.
If the read operation fails, the
failed()method of the
CompletionHandlerwill get called instead.
Writing Data
Just like with reading, you can write data to an AsynchronousFileChannelin 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 AsynchronousFileChannelalso enables you to write data asynchronously. Here is a full Java
AsynchronousFileChannelwrite 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
AsynchronousFileChannelis opened in write mode. Then a
ByteBufferis created and some data written into it. Then the data in the
ByteBufferis written to the file. Finally the example checks the returned
Futureto
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
Pathpoints 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 AsynchronousFileChannelwith a
CompletionHandlerto tell you when the write is complete instead of a
Future. Here is an example of writing data to the
AsynchronousFileChannelwith
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
ByteBufferis used as attachment - the object which is passed on to the
CompletionHandler's methods.
相关文章推荐
- Java NIO Files
- java环境配置
- java中Random类和Math类中的random方法的联系和区别
- Java NIO Path
- Spring Boot -- 配置切换指南
- farmer and cow 广搜 java
- Java反射机制的简介
- 2145334赵文豪《Java程序设计》第2周学习总结
- Java NIO Path
- Java NIO vs. IO
- Java容器
- Java中的赋值问题
- Java NIO Pipe
- Java NIO DatagramChannel
- 20145218 《Java程序设计》第二周学习总结
- java多线程典型例子及分析
- red and black 杭电1312 java深搜
- java的垃圾回收机制浅理解
- mybatis与spring的整合
- 20145330孙文馨 《Java程序设计》第二周学习总结