使用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你需要了解多少,来看看这篇文章】
推荐阅读
- EXCEL快速提取文件夹内的文件名
- Linux」简单认识认识ELF文件
- 如何挖掘Web目录文件泄漏和其它Web漏洞利用?
- 文件同步工具 SyncTime for mac
- 小白一键重装系统备份文件在哪
- 在Windows和Linux中找出磁盘分区使用的文件系统,就是这么简单
- 文件系统与数据库系统的区别和联系
- 金山文档怎么导出excel文件?
- Apache中.htaccess文件利用的总结与新思路拓展
- 强制删除苹果描述文件可移除否,苹果描述文件怎么彻底删除?