Java NIO-AsynchronousFileChannel

Java NIO 异步文件通道,原文地址:http://tutorials.jenkov.com/java-nio/asynchronousfilechannel.html

Java 7 NIO 中添加了 AsynchronousFileChannel。通过 AsynchronousFileChannel,我们可以异步地从文件中读写数据。本教程将会解释 AsynchronousFileChannel 的用法。

创建异步文件通道

创建异步文件通道的语法:

1
2
3
Path path = Paths.get("data/test.xml");
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);

读取数据

通过 AsynchronousFileChannel 读取数据有两种方式,下面我们慢慢叙来。

Reading Data Via a Future

用法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();

Reading Data Via a CompletionHandler

用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fileChannel.read(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>(){
@Overried
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){
}
});

写入数据

和读取数据一样,写入数据也有两种形式,下面我们一一道来。

Writing Data Via a Future

用法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.");

Writing Data Via a CompletionHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Path path = Paths.get("data/test-write.txt");
if(!Files.exists(path)) {
Files.createFile(path);
}
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.oepn(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();
}
});

至此,Java NIO 教程十七篇终于看完了。。。接下来要赶紧把《Tomcat 权威指南》和《深入剖析Tomcat》看完了!