在Java中查找特定文件夹

时间:2014-03-31 22:01:35

标签: java file recursion io

我希望找到Java中特定文件夹的路径,作为更大程序的一部分  我所拥有的是一个递归函数,它检查起始目录中包含的每个文件,如果找到我要查找的文件夹,它会将路径作为字符串分配给变量。以下代码有效:

//root is the starting directory and name is the folder I am looking for
private void findDir(File root, String name)  
{  
    if (root.getName().equals(name))
    {
        toFind = root.getAbsolutePath();
    }

    File[] files = root.listFiles();

    if(files != null)
    {
        for (File f : files)  
        {
            if(f.isDirectory())
            {   
                findDir(f, name);
            }
        }
    }
}

这有效,但我不喜欢我必须使用'查找'变量。我的问题是有没有办法让方法返回一个String而不是void?这也将保存程序在找到正在查找的文件后检查系统中的所有其他文件 我正在考虑这样的事情,但即使找到该文件夹​​,以下代码也将返回null。

private String findDir(File root, String name)
{
    if (root.getName().equals(name))
    {
        return root.getAbsolutePath();
    }

    File[] files = root.listFiles();

    if(files != null)
    {
        for (File f : files)  
        {
            if(f.isDirectory())
            {   
                return findDir(f, name);
            }
        }
    }

    return null; //???
}

1 个答案:

答案 0 :(得分:1)

这是因为树中没有子目录的第一个目录将返回null,因为您指定listFiles()的结果是null,返回null用于整个递归。它并不是很明显,但可以通过更改for循环中的行为来解决这个问题。您应该测试结果是否为null,而不是直接在for循环中返回结果,如果是,则继续。但是,如果您有非空结果,则可以向上传播结果。

private String findDir(File root, String name)
{
    if (root.getName().equals(name))
    {
        return root.getAbsolutePath();
    }

    File[] files = root.listFiles();

    if(files != null)
    {
        for (File f : files)  
        {
            if(f.isDirectory())
            {   
                String myResult = findDir(f, name);
                //this just means this branch of the
                //recursion reached the end of the
                //directory tree without results, but
                //we don't want to cut it short here,
                //we still need to check the other
                //directories, so continue the for loop
                if (myResult == null) {
                    continue;
                }
                //we found a result so return!
                else {
                    return myResult;
                }
            }
        }
    }

    //we don't actually need to change this. It just means we reached
    //the end of the directory tree (there are no more sub-directories
    //in this directory) and didn't find the result
    return null;
}

编辑:使用Boris the Spider的建议,我们实际上可以删除if语句,以避免continue语句有些笨重的性质,以及使代码更加重要。而不是:

if (myResult == null) {
    continue;
}
else {
    return myResult;
}

我们可以滑到它的位置:

if (myResult != null) {
    return myResult;
}

将使用相同的逻辑进行评估,并减少整体代码。