版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/88126706
Java新AIO/NIO2:AsynchronousFileChannel以CompletionHandler方式读
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Test {
private AsynchronousFileChannel fileChannel;
private MyCompletionHandler completionHandler;
private ByteBuffer buffer;
private final int COUNT = 3;
public static void main(String[] args) {
try {
new Test();
} catch (Exception e) {
e.printStackTrace();
}
}
public Test() throws Exception {
Path path = Paths.get("D:\\code\\file.txt");
System.out.println("文件路径:" + path);
fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
buffer = ByteBuffer.allocate(COUNT);
completionHandler = new MyCompletionHandler();
long size = fileChannel.size();
System.out.println("文件长度:" + size);
System.out.println("文件内容:");
printer(path.toString());
System.out.println("==========");
int pos = 0;
int i = 0;
while (pos < size) {
System.out.println("第" + (++i) + "次读");
fileChannel.read(buffer, pos, buffer, completionHandler);
pos = pos + COUNT;
// 如果不中断while循环若干时间,读出的数据不准、错乱。
Thread.sleep(5);
}
}
private class MyCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
@Override
public void completed(Integer result, ByteBuffer buf) {
System.out.println("读取数据长度:" + result + ",内容:" + new String(buf.array(), 0, result));
buf.clear();
}
@Override
public void failed(Throwable t, ByteBuffer attachment) {
t.printStackTrace();
}
}
// 打印path指向的文件中的内容。
private void printer(String path) throws Exception {
InputStream is = new FileInputStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String str = null;
while (true) {
str = reader.readLine();
if (str != null)
System.out.println(str);
else
break;
}
is.close();
}
}
输出:
文件路径:D:\code\file.txt
文件长度:10
文件内容:
0123456789
==========
第1次读
读取数据长度:3,内容:012
第2次读
读取数据长度:3,内容:345
第3次读
读取数据长度:3,内容:678
第4次读
读取数据长度:1,内容:9