![](/img/trans.png)
[英]Java - Find specific files (based on conditions) inside a given folder
[英]Find specific folder in Java
我正在寻找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循环内返回结果,如果是,则继续。 但是,如果结果为非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;
}
编辑 :根据蜘蛛的鲍里斯(Boris)的建议,我们实际上可以精简if
语句,以避免continue
语句的笨拙性质,并使代码更具体一点。 代替:
if (myResult == null) {
continue;
}
else {
return myResult;
}
我们可以直接滑入它的位置:
if (myResult != null) {
return myResult;
}
它将使用完全相同的逻辑进行评估,并且所需的总体代码更少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.