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中網絡通信