I am trying to find a file in a root directory and it’s sub-directories.
Step1- Find a directory in a specified path.
Step2- If the above directory is found, look for a file in one of it’s sub-directory.
For this, I use the below code snippet that search recursively.. Now, the issue here is, how do I break out of the recursion when it meets both of my above requirements..?
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;
}
Thanks,
DK
Now, pass “test2.adv” as third param when you invoke findFile. That’s more interesting than hardcoding it.
Also please note that multiple files could match your search, this function doesn’t handle it well, it will return the first one found.