异步文件通道Java NIO你需要了解多少,来看看这篇文章( 二 )

使用CompletionHandler写入数据我们也可以使用 CompletionHandler代替Future向AsynchronousFileChannel写入数据,这种方式可以更加直接的知道写入过程是否完成 。下面是示例程序:
Path path = Paths.get("data/test-write.txt");if(!Files.exists(path)){Files.createFile(path);}AsynchronousFileChannel fileChannel =AsynchronousFileChannel.open(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>() {@Overridepublic void completed(Integer result, ByteBuffer attachment) {System.out.println("bytes written: " + result);}@Overridepublic void failed(Throwable exc, ByteBuffer attachment) {System.out.println("Write failed");exc.printStackTrace();}});当写入程序完成时,CompletionHandler的completed()方法将会被调用,相反的如果写入失败则会调用failed()方法 。
要留意CompletionHandler的方法的参数 attachemnt是怎么使用的 。
最后

私信回复 资料 领取一线大厂Java面试题总结+阿里巴巴泰山手册+各知识点学习思维导+一份300页pdf文档的Java核心知识点总结!
这些资料的内容都是面试时面试官必问的知识点,篇章包括了很多知识点,其中包括了有基础知识、Java集合、JVM、多线程并发、spring原理、微服务、Netty 与RPC 、Kafka、日记、设计模式、Java算法、数据库、Zookeeper、分布式缓存、数据结构等等 。

【异步文件通道Java NIO你需要了解多少,来看看这篇文章】


推荐阅读