gpt4 book ai didi

java - 在Java中查找特定文件夹

转载 作者:行者123 更新时间:2023-11-30 11:20:21 26 4
gpt4 key购买 nike

作为更大程序的一部分,我正在寻找 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);
}
}
}
}

这行得通,但我不喜欢必须使用“toFind”变量这一事实。我的问题是有没有办法让方法返回一个 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; //???
}

最佳答案

这是因为如果 listFiles() 的结果为null,为整个递归返回null。这不是很明显,但是可以通过更改 for 循环中的行为来解决。与其直接在 for 循环中返回结果,不如测试结果是否为 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())
{
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;
}

编辑:使用蜘蛛鲍里斯的建议,我们实际上可以剥离 if 语句以避免 continue 语句有些笨拙的性质,并使代码更加切题。而不是:

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

我们可以原地踏步:

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

这将使用完全相同的逻辑进行评估并占用更少的整体代码。

关于java - 在Java中查找特定文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22773090/

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