对于给定的位置和文件名,文件路径返回'null'

时间:2012-11-23 08:26:28

标签: java

有人可以告诉我代码中的错误。我正在尝试在目录路径中搜索名为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:

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

编辑:更新:

我找到了另一种方式。如果有错误请更正:将filePath声明为静态变量

    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;
     }
       }

}

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

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

if(filePath.endsWith(memberPath))
{
    return filePath;
}

答案 2 :(得分: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)