gpt4 book ai didi

java.nio.file.Paths - 如何在迭代时跳过无法访问的文件/文件夹

转载 作者:行者123 更新时间:2023-12-02 17:50:34 27 4
gpt4 key购买 nike

我正在编写代码来迭代我可以访问的所有文件夹。但是,当文件夹无法访问时,我的程序会停止。

我如何绕过该文件夹并继续寻找其他文件夹?或者,换句话说,我如何显示我有权访问的文件夹和文件?

我正在使用 java.nio.file.Paths (Java 8)。

这是我的代码:

import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Paths;

// Test File D:\TEST\test.jpg
public class TestIteration{

// Main
public static void main(String[] args) throws Exception {
// Iterate through folders
String rootFolder = "c:\\";
WalkDirTree(rootFolder); // Walks through directory tree and print names of directories/files.
}


// Prints all file/directory names in the entire directory tree
private static void WalkDirTree(String rootFolder) throws Exception {
Files.walk(Paths.get(rootFolder)).forEach(path -> {
System.out.println(path);
});

System.out.println("_______________________________________DONE");
}

}

最佳答案

如果无法访问您指的是“不可读”,那么我认为您可以使用 Files#isReadable ;来自其文档:

Tests whether a file is readable. This method checks that a file exists and that this Java virtual machine has appropriate privileges that would allow it open the file for reading. Depending on the implementation, this method may require to read file permissions, access control lists, or other file attributes in order to check the effective access to the file. Consequently, this method may not be atomic with respect to other file system operations.

您的代码如下所示:

Files.walk(Paths.get(rootFolder)).filter(Files::isReadable).forEach(path -> {
System.out.println(path);
});

关于java.nio.file.Paths - 如何在迭代时跳过无法访问的文件/文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982666/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com