我正在寻找 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; //???
}
最佳答案
这是因为树中没有子目录的第一个目录将返回 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;
}
它将使用相同的精确逻辑进行评估,并且需要更少的总体代码。
关于java - 在Java中查找特定文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22773090/