【问题标题】:counting level of nesting within a file folder计算文件夹内的嵌套级别
【发布时间】:2017-07-08 13:32:45
【问题描述】:

当试图计算文件路径中有多少子目录时,最好的方法是什么?

例如,我想检查 /a/b/c/d/file.txt 中的 file.txt 与根文件夹之间只有 3 个子目录。有没有我没听说过的方法?

目前我正在使用一种方法来计算 file.txt 中有多少父目录,方法类似于:

boolean lessThan3Subdirectories(File textFile){
File homeFile = new File (/a);
if (textFile.getParent()
           .getParentFile()
           .getParentFile()
           .getParentFile() 
            != homeFile){
return false; 
} else {
return true;
}

我对这种方法的问题是它被硬编码为检查 3 并且总是 3 但我实际上并不关心只要它小于 3 就需要多少父目录。(/a/b /file.txt 就可以了)

我的另一个选择是只获取文件路径字符串并计算文件和主文件夹之间出现“/”的次数。但是,该方法的问题是我无法解释包含转义 / 的文件名(即“/”)

【问题讨论】:

  • 为什么不能使用循环?

标签: java file nested filepath subdirectory


【解决方案1】:

好的。这是您可以编写递归函数的东西。我可以给你一个骨架。此函数将返回您的文件存在的深度。

        int recurFunc(String path, String fileNameToCheck){

            //1. count all the files in given directory
            //2. Write a for loop for each file checking if its a directory or file.
            //3. if its a directory call recurFunc with directory name appended. (return 1 + recurFunc(directorypath)). This will give you the depth
            //4. if its a file check if its your required file or not
            //5. if its your file return 0;else skip 

        }

此外,如果您想将搜索限制为 3 个级别,只需将级别传递给 recurFunc(String path, String fileName, int level) 并在进入目录时将级别降低 1。当级别为 0 时,只需检查该级别是否是否包含您的文件。

【讨论】:

    猜你喜欢
    • 2011-08-27
    • 2023-04-02
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 2016-06-13
    相关资源
    最近更新 更多