【问题标题】:How to find sub-directories in a directory/folder?如何在目录/文件夹中查找子目录?
【发布时间】:2012-11-12 01:52:31
【问题描述】:

我正在寻找一种方法来获取给定目录中所有目录的名称,而不是文件。

例如,假设我有一个名为 Parent 的文件夹,其中有 3 个文件夹:Child1 Child2Child3

我想获取文件夹的名称,但不关心内容,或者 Child1、Child2 等中的子文件夹的名称。

有没有简单的方法来做到这一点?

【问题讨论】:

  • 你知道它可以有多少层吗?或者它可以是任何数字?
  • @Quoi 不,这不是作业。
  • @Aaron 深度不应超过 2 层。含义一个父文件夹,一个子子文件夹,然后应该没有比这更深的了。

标签: java directory java-io


【解决方案1】:

如果您使用的是 java 7,您可能想尝试使用

中提供的支持
package java.nio.file 

如果您的目录有很多条目,它将能够开始列出它们而无需先将它们全部读入内存。在 javadoc 中阅读更多内容:http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path,%20java.lang.String)

这也是适合您需要的示例:

public static void main(String[] args) {
    DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
        @Override
        public boolean accept(Path file) throws IOException {
            return (Files.isDirectory(file));
        }
    };

    Path dir = FileSystems.getDefault().getPath("c:/");
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {
        for (Path path : stream) {
            // Iterate over the paths in the directory and print filenames
            System.out.println(path.getFileName());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【讨论】:

  • 在 Java 8 上,您可以简化为: Files.newDirectoryStream(dir, p -> Files.isDirectory(p))
【解决方案2】:

您可以使用String[] directories = file.list() 列出所有文件名, 然后使用循环检查每个子文件并使用file.isDirectory()函数获取子目录。

例如:

File file = new File("C:\\Windows");
String[] names = file.list();

for(String name : names)
{
    if (new File("C:\\Windows\\" + name).isDirectory())
    {
        System.out.println(name);
    }
}

【讨论】:

  • What's "C\\Windows\\" , list() 返回 absolutePath
  • 听起来不错!如果我不确切知道路径在某个点之前会是什么,说“..\\Projects\\Tests\\Test1”是目录中唯一已知的部分,我仍然可以这样做吗方式?
  • 您的意思是输入将是相对路径?因为如果我们不提供绝对路径,程序会将其视为运行程序当前路径的相对路径。例如,如果程序的路径是C:\\Project\\Test,我们输入一个路径名abc,那么程序会将其视为C:\\Project\\Test\\abc
  • @bhuang3 抱歉,我不清楚。如果我不知道 Project 目录之前的路径怎么办?我想在多台计算机上运行它,但每次都来自我的 Eclipse 项目。我的 File 对象在初始化时会是什么样子?
【解决方案3】:
public static void displayDirectoryContents(File dir) {
    try {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("Directory Name==>:" + file.getCanonicalPath());
                displayDirectoryContents(file);
            } else {
                System.out.println("file Not Acess===>" + file.getCanonicalPath());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

====内部类/方法提供文件=URL ======

    File currentDir = new File("/home/akshya/NetBeansProjects/");
    displayDirectoryContents(currentDir);
}

【讨论】:

    猜你喜欢
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    相关资源
    最近更新 更多