编程语言
首页 > 编程语言> > java – Files.list和Files.walkFileTree和Files.walk有什么区别,maxdepth = 1?

java – Files.list和Files.walkFileTree和Files.walk有什么区别,maxdepth = 1?

作者:互联网

如果我只想在目录的第一级对文件执行某些操作,
使用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;
    }
});

Files.list(directory)
    .forEach(path -> {
        try {
            doSomething(path);
        } catch (IOException exc) {
            // log exc
        }
    });

Files.walk(directory, 1)
    .forEach(path -> {
        try {
            doSomething(path);
        } catch (IOException exc) {
            // log exc
        }
});

解决方法:

使用以下代码作为测试,我得到了问题的悬而未决. walk *和list之间的主要区别在于list(dir)在目录dir中提供了一个文件流,而walk *方法都遍历其参数的子树,包括子树的根 – 目录本身.

walk和walkFileTree之间的区别在于它们为步行树提供了不同的接口:walkFileTree接受FileVisitor,walk给出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);
    }
}

标签:java,java-nio-file,nio2
来源: https://codeday.me/bug/20190611/1219487.html