NIO使用walkFiles遍历目录
FileVisitor接口
public interface FileVisitor<T> {
FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs)throws IOException;
FileVisitResult visitFile(T file, BasicFileAttributes attrs)throws IOException;
FileVisitResult visitFileFailed(T file, IOException exc) throws IOException;
FileVisitResult postVisitDirectory(T dir, IOException exc) throws IOException;
}
visitFile
The visitFile() method is invoked for a file in a directory. Usually, this method returns a CONTINUE result or a TERMINATE result(这个方法在访问文件的时候被调用,一般的,这个方法返回FileVisistResult.CONTINUE或者是FileVisistResult.TERMINATE类型的结果)
preVisitDirectory
The preVisitDirectory() method is invoked for a directory before visiting its entries(这个方法在访问目录之前被调用)
visitFileFailed
The visitFileFailed method is invoked when the file cannot be accessed for any of several different reasons, such as the file’s attributes cannot be read or a directory cannot be opened.(当这个文件因为某些原因不能够被访问的时候会调用这个方法,如如这个文件属性没有权限读或者是文件目录不能打开)
postVisitDirectory
The postVisitDirectory method is invoked after all entries in the directory (and any descendants) have been visited or the visit has ended suddenly (that is, an I/O error has occurred or the visit has programmatically aborted)(当文件目录被全部访问结束的时候或者访问被突然中断的时候会调用这个方法)
FileVisitResult
public enum FileVisitResult {
CONTINUE,
TERMINATE,
SKIP_SUBTREE,
SKIP_SIBLINGS;
}
- FileVisitResult.CONTINUE: This visit result indicates that the traversal process should continue
- FileVisitResult.SKIP_SIBLINGS: This visit result indicates that the traversal process should continue without visiting the siblings of this file or directory
- FileVisitResult.SKIP_SUBTREE: This visit result indicates that the traversal process should continue without visiting the rest of the entries in this directory
- FileVisitResult.TERMINATE: This visit result indicates that the traversal process should terminate.
测试用例:
@Test
public void walkFiles(){
Path path = Paths.get("D:\\user");
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println(file.toAbsolutePath());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println(exc);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return super.postVisitDirectory(dir, exc);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
结果:
D:\user\driving\1.jpg
D:\user\driving\2.jpg
D:\user\driving\3.jpg
D:\user\driving\4.jpg
D:\user\identity\5.jpg
D:\user\identity\6.jpg
D:\user\img\7.jpg
D:\user\img\8.jpg
D:\user\img\9.jpg
D:\user\img\10.jpg
D:\user\img\11.jpg
D:\user\img\12.jpg
D:\user\img\13.jpg