要实现 FileVisitor 接口就要实现接口上的所有方法,但是你有可能只需要实现其中的一两个方法,因此这对于你来说会显得很麻烦。在这种情况下,你可以继承 SimpleFileVisitor 类,它是 FileVisitor 接口的一个实现。这样,你就仅仅只需要覆盖你需要的方法即可。
例如,你可能需要遍历目录树并打印所有目录的名字。要实现这个目标,只需要覆盖 postVisitDirectory() 和 visitFileFailed() 方法,参考代码如下:
class ListTree extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
System.out.println("Visited directory: " + dir.toString());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.out.println(exc);
return FileVisitResult.CONTINUE;
}
}
正如你所见,上面代码忽略了 preVisitDirectory() 和 visitFile() 两个方法。
文章来源:
http://www.aptusource.org/2014/04/nio-2-simplefilevisitor/
分享到:
相关推荐
Java I/O, NIO, and NIO.2 is a power-packed book that accelerates your mastery of Java's various I/O APIs. In this book, you'll learn about classic I/O APIs (File, RandomAccessFile, the stream classes ...
java NIO.zip
New I/O (NIO), and NIO.2 categories. You learn what each category offers in terms of its capabilities, and you also learn about concepts such as paths and Direct Memory Access. Chapters 2 through 5 ...
java nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava ...
这是一本介绍java io以及nio相关知识的书,书中对知识的讲解通俗易懂,是学习java nio以及复习java io相关知识的必备书籍。注意:本书为英文版!!!
Java NIO.pdf Java NIO.pdf Java NIO.pdf Java NIO.pdf Java NIO.pdf Java NIO.pdf
蔚来-NIO.US-新车上市,蔚来可期.pdf
This book covers all the important aspects involved in developing NIO.2-based applications. It provides clear instructions for getting the most out of NIO.2 and offers many exercises and case studies ...
Apress.Pro.Java.7.NIO.2.2011
Java NIO,Ron Hitchens 著,中文版 裴小星 译,Pro Java 7 NIO.2,Anghel Leonard 著,pdf文字版带书签,无安全限制
Pro Java 7 NIO.2.pdf,2011 by Anghel Leonard
Pro Java 7 NIO.2 – PDF Books
This book covers all the important aspects involved in developing NIO.2-based applications. It provides clear instructions for getting the most out of NIO.2 and offers many exercises and case studies ...
java.nio 包定义了缓冲区类,这些类用于所有 NIO API。java.nio.charset 包中定义了字符集 API,java.nio.channels 包中定义了信道和选择器 API。每个子包都具有自己的服务提供程序接口 (SPI) 子包,SPI 子包的...
JavaNIO.pdf
找了好久,终于找到了,java刷新同步获取网络资源
所以本章,我们就来主要介绍 java.nio.file 中常用的类和模块,大致如下: Path 路径:Paths 模块和 Path 工具类介绍 Files 文件:File 和 FileSystems 工具类介绍 文件管理服务:WatchService 、PathMatcher 等等...
用java.nio.*进行网络编程
Java NIO.docx