2

有人可以告诉我我在代码中哪里错了。我正在尝试搜索filename在目录路径中命名的特定文件并尝试返回filepath但它总是返回null

这是我正在使用的代码:

public String walk( String path, String filename ) {
String filePath = null;
    File root = new File( path );
    File[] list = root.listFiles();

    for ( File f : list ) {
        if ( f.isDirectory() ) {
            walk( f.getAbsolutePath(),filename );
           }
        else if (f.getName().equalsIgnoreCase(filename)){
            System.out.println( "File:" +f.getAbsolutePath() );
            filePath= f.getAbsolutePath();
           if(filePath.endsWith(memberPath)){
               System.out.println( "Found: Should exit");
               break;
           }
        }
     }
    System.out.println( "OUT of for:"  );
    return filePath;
}

它打印
出:

 OUT of for:    

 File:d:\IM\EclipseWorkspaces\runtime-EclipseApplication\SIT\So\mmm\aaa\xxx.c

Should exit

OUT of for:

OUT of for:

我不明白为什么它仍然回到循环

编辑:更新:

我找到了另一种方法。如果有问题请更正:将文件路径声明为静态变量

    public static void walk( String path, String filename ) {

    File root = new File( path );
    File[] list = root.listFiles();

    for ( File f : list ) {
       if ( f.isDirectory() ) {
            walk( f.getAbsolutePath(),filename );
           }
        else if (f.getName().equalsIgnoreCase(filename) && f.getAbsolutePath().endsWith(memberPath)){
             System.out.println( "Should exit");
             filePath = f.getAbsolutePath();
             break;
     }
       }

}
4

3 回答 3

2

您不需要memberPath. 将您的代码更改为如下所示:

public String walk(String path, String filename) {
    String filePath = null;
    File root = new File(path);
    File[] list = root.listFiles();

    for (File f : list) {
        if (f.isDirectory()) {
            walk(f.getAbsolutePath(), filename);
        } else if (f.getName().equalsIgnoreCase(filename)) {
            System.out.println("File:" + f.getAbsolutePath());
            System.out.println("Found: Should exit");
            filePath = f.getAbsolutePath();
            break;
        }
    }
    return filePath;
}
于 2012-11-23T08:35:47.627 回答
1

找到后立即返回文件路径:

if(filePath.endsWith(memberPath))
{
    return filePath;
}
于 2012-11-23T08:32:06.977 回答
0
public String walk(String path, String filename) {
String filePath = null;
File root = new File(path);
File[] list = root.listFiles();

for (File f : list) {
    if (f.isDirectory()) {
        // store the filePath 
        filePath = walk(f.getAbsolutePath(), filename);    
    } else if (f.getName().equalsIgnoreCase(filename) && f.getAbsolutePath().endsWith(memberPath)) {
        System.out.println("File:" + f.getAbsolutePath());
        System.out.println("Found: Should exit");
        filePath = f.getAbsolutePath();
        break;
    }
  if (filePath != null) {
    break;
  }
}
return filePath;

}

编辑:添加 f.getAbsolutePath().endsWith(memberPath)

于 2012-11-23T09:18:41.007 回答