and*_*bak 5 java java.nio.file nio2
如果我想要做一些文件只对目录的第一级,是有使用之间的差异Files.list(...)或Files.walkFileTree(...)或Files.walk(...)?
Files.walkFileTree(directory, Collections.emptySet(), 1, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
doSomething(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
// log exc
return FileVisitResult.CONTINUE;
}
});
Run Code Online (Sandbox Code Playgroud)
与
Files.list(directory)
.forEach(path -> {
try {
doSomething(path);
} catch (IOException exc) {
// log exc
}
});
Run Code Online (Sandbox Code Playgroud)
与
Files.walk(directory, 1)
.forEach(path -> {
try {
doSomething(path);
} catch (IOException exc) {
// log exc
}
});
Run Code Online (Sandbox Code Playgroud)
使用以下代码作为测试,我得到了问题的悬而未决.之间的主要区别walk*和list是list(dir)给人流目录中的文件 dir,而这两个walk*方法走路子树的说法,包括树,目录本身的根源.
walk和之间的区别在于walkFileTree它们为树的行走提供了不同的接口:walkFileTreetake FileVisitor,walkgive Stream<Path>.
public class FilesTest {
public static void main(String[] args) {
final String pwd = System.getProperty("user.dir");
System.out.println("Working Directory = " + pwd);
Path dir = Paths.get(pwd);
System.out.println("Files.walk");
try {
Files.walk(dir, 1).forEach(path -> FilesTest.doSomething("walk", path));
} catch (IOException e) {
logException("walk", e);
}
System.out.println("Files.walkFileTree");
try {
Files.walkFileTree(dir, Collections.emptySet(), 1, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
doSomething("visitFile", file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
logException("visitFile", exc);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
logException("walkFileTree", e);
}
System.out.println("Files.list");
try {
Files.list(dir).forEach(path -> FilesTest.doSomething("dir", path));
} catch (IOException e) {
logException("dir", e);
}
}
private static void logException(String title, IOException e) {
System.err.println(title + "\terror: " + e);
}
private static void doSomething(String title, Path file) {
System.out.println(title + "\t: " + file);
}
}
Run Code Online (Sandbox Code Playgroud)