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

标签 java directory iteration

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

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

我正在使用 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/

相关文章:

caching - 当我重复使用旧的缓存数据太多时间时,Spark Dataframe 突然变得非常慢

java - 如何在 JPanel+image 上部分添加不同的形状

java - 可以避免 google 端点 URL 中的版本号

android - 如何在 Android Root 上使用我的应用程序名称创建文件夹

c# - 检查文件夹是否有文件

javascript - JavaScript 'for' 循环中的执行顺序是什么?

Python迭代不进入if-elif

java - Java中的回车\换行

java - 在 JLabel 中显示表格上的项目名称

python - 查找子目录路径的最有效方法