android - 递归搜索文件

标签 android

我正在尝试在根目录及其子目录中查找文件。

Step1- 在指定路径中查找目录。 第 2 步 - 如果找到上述目录,请在其中一个子目录中查找文件。

为此,我使用下面的递归搜索代码 fragment 。现在,这里的问题是,当递归满足我的上述两个要求时,我如何打破递归......?

 boolean bFileFound = false;
File  fileFound     = null;

private void findFile( File aFile, String sDir ){

    String  filePath = aFile.getAbsolutePath();

    if( aFile.isFile() && filePath.contains( sDir ) ){

              if( aFile.getName().contains( "test2.adv")){
                  Log.d(TAG, "[FILE] " + aFile.getName() );
                  fileFound = aFile;
                  bFileFound = true;
              }

             // return true;
    }else if( aFile.isDirectory() ){

        String sDirName = aFile.getName();
        Log.d(TAG, "[DIR] " + sDirName );

        if( sDirName.contains( sDir ) ){

            Log.d( TAG, "Found the directory..& Absolute Path = " + aFile.getAbsolutePath());
            sDir = sDirName;
        }

        File[] listFiles = aFile.listFiles();

        if( listFiles != null ){

          for( int i = 0; i < listFiles.length; i++ ){

              if(bFileFound)
                    return;

            findFile( listFiles[ i ], sDir );
          }
        }else{

          Log.d( TAG,  " [ACCESS DENIED]" );
        }
    }

   // return null;
}

谢谢, DK

最佳答案

/**
 * Search file a file in a directory. Please comment more here, your method is not that standard.
 * @param file the file / folder where to look our file for.
 * @param sDir a directory that must be in the path of the file to find
 * @param toFind the name of file we are looking for. 
 * @return the file we were looking for. Null if no such file could be found.
 */
private File findFile( File aFile, String sDir, String toFind ){
    if( aFile.isFile() && 
            aFile.getAbsolutePath().contains( sDir ) && 
            aFile.getName().contains( toFind ) ) {
                        return aFile;
        } else if( aFile.isDirectory() ) {
        for( File child : aFile.listFiles() ){
            File found = findFile( child, sDir, toFind );
                    if( found != null ) { 
                        return found;
                    }//if
        }//for
    }//else
   return null;
}//met

现在,调用 findFile 时将“test2.adv”作为第三个参数传递。这比硬编码更有趣。

另请注意,多个文件可能与您的搜索相匹配,此函数不能很好地处理它,它将返回找到的第一个文件。

关于android - 递归搜索文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10589298/

相关文章:

java - 我可以在 Eclipse 中使用 Android SDK Java 为平板电脑开发吗?

Android:运行时错误 'Unable to create directory',使用类 DownloadManager,方法 setDestinationInExternalPublicDir

java - 如何将微调器下拉值转换为整数

android - 上传前从相机裁剪图像(Phonegap)

android - 很难将 child 与另一个 child 之间的最左和最右对齐

android - 改造错误:-预期为BEGIN_ARRAY,但在路径$处为BEGIN_OBJECT

android - 为什么 blobstore 上传代码有重定向 url

android - 请通过更新 google-services 插件或 updati 的版本来修复版本冲突

android - 对于具有多个帐户的 Android 应用程序,GCM 注册 ID 的唯一性如何?

java - Android - 如何将从 Firebase 存储下载的照片保存到手机?