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を出力します。

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

}
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 に答える