AIO
什么是AIO,既是异步IO,这里的异步对照io第一篇里面异步IO流程图,在请求数据和回传数据两个阶段都是交给操作系统内核态异步处理,无需用户态阻塞等待,Java1.7中新增处理异步IO的类,AsynchronousFileChannel、AsynchronousServerSocketChannel、AsynchronousSocketChannel、AsynchronousChannelGroup(线程池管理),这里需要注意一点,异步IO只在Windows上真正实现。
1.AIO,文件读取
private static void readFile() throws IOException, InterruptedException, ExecutionException {
Path path = Paths.get("C:\\Users\\baopz\\Desktop\\图片\\test\\1.txt");
AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
//16k
ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 14);
Future<Integer> future = asynchronousFileChannel.read(buffer, 0);
System.out.println(future.get());
asynchronousFileChannel.close();
}
2.AIO,带CompletionHandler处理
这里使用了CompletionHandler的回调处理机制,在任务处理完毕后,Handler会自行根据传入的数据以及实现的逻辑进行结果处理,包括异常处理。
public static void readFileWithCompletedHandler() throws IOException, InterruptedException {
Path path = Paths.get("C:\\Users\\baopz\\Desktop\\图片\\test\\1.gif");
AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
//16k
ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 14);
asynchronousFileChannel.read(buffer, 0, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
System.out.println("读取文件已经完成,读取长度" + result);
}
@Override
public void failed(Throwable exc, Object attachment) {
System.out.println("读取文件错误");
}
});
asynchronousFileChannel.close();
}
3.AIO,文件拷贝
/**
* 异步文件拷贝
* @throws IOException
*/
public static void copyFile() throws IOException {
Path path = Paths.get("C:\\Users\\baopz\\Desktop\\图片\\test\\1.gif");
Path target = Paths.get("C:\\Users\\baopz\\Desktop\\图片\\test\\2.gif");
if (Files.notExists(target)) {
Files.createFile(target);
}
ExecutorService executorService = Executors.newCachedThreadPool();
AsynchronousFileChannel readChannel = AsynchronousFileChannel.open(path, Collections.singleton(StandardOpenOption.READ),executorService );
AsynchronousFileChannel writeChannel = AsynchronousFileChannel.open(target, StandardOpenOption.WRITE);
//16k
final ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 14);
readChannel.read(buffer, 0, writeChannel, new CompletionHandler<Integer, AsynchronousFileChannel>() {
@Override
public void completed(Integer result, AsynchronousFileChannel attachment) {
buffer.flip();
Future<Integer> future = attachment.write(buffer, 0);
try {
System.out.println(future.get());
attachment.close();
} catch (IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable exc, AsynchronousFileChannel attachment) {
System.out.println("异常情况" + exc.toString());
try {
attachment.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
if(readChannel.isOpen()) {
readChannel.close();
}
executorService.shutdown();
}
4.AIO文件网络通信拷贝
1.server端
private static void server() throws IOException, InterruptedException, ExecutionException {
AsynchronousChannelGroup group = AsynchronousChannelGroup.withCachedThreadPool(Executors.newCachedThreadPool(), 5);
AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8888));
System.out.println("绑定成功。");
Future<AsynchronousSocketChannel> future = serverSocketChannel.accept();
//阻塞接收连接
AsynchronousSocketChannel asynchronousSocketChannel = future.get();
//16k
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1 << 14);
asynchronousSocketChannel.read(byteBuffer);
Path path = Paths.get("C:\\Users\\baopz\\Desktop\\图片\\test\\4.gif");
if (Files.notExists(path)) {
try {
Files.createFile(path);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
ExecutorService executorService1 = Executors.newCachedThreadPool();
AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, Collections.singleton(StandardOpenOption.WRITE), executorService1);
byteBuffer.flip();
while (!asynchronousFileChannel.write(byteBuffer, 0).isDone()) {
TimeUnit.MILLISECONDS.sleep(500);
}
asynchronousFileChannel.close();
executorService1.shutdown();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
serverSocketChannel.close();
if (!group.isShutdown()) {
group.shutdown();
}
}
2.客户端
private static void client() throws IOException, InterruptedException, ExecutionException {
AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open();
Future<Void> voidFuture = asynchronousSocketChannel.connect(new InetSocketAddress("127.0.0.1", 8888));
//阻塞等待连接
voidFuture.get();
System.out.println("连接成功");
Path path = Paths.get("C:\\Users\\baopz\\Desktop\\图片\\test\\1.gif");
//16k
final ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 14);
AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
Future<Integer> integerFuture = asynchronousFileChannel.read(buffer, 0);
int result = integerFuture.get();
System.out.println(result);
buffer.flip();
Future<Integer> integerFuture1 = asynchronousSocketChannel.write(buffer);
try {
System.out.println("写出去数据:" + integerFuture1.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
asynchronousSocketChannel.close();
}
总结,到这里Java I/O相关操作,介绍完毕,从Java 1.0开始的InputStrem和OutputStream,在Java 4中出现的Buffer、Channel、Selector,在Java 7出现的Path、Files、FilesSystems、AsynchronousFileChannel、AsynchronousServerSocketChannel等等都介绍完毕了,下一篇,记录Java中网络通信