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) {
}
});