Question

I want to search for a particular file in my sd card . So i am trying to list complete files and search for the pattern. Please see code below

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String root_sd = Environment.getExternalStorageDirectory().toString();
    file = new File(root_sd);
    listfiles( new File(root_sd));

}

public void listfiles(File file) {

    //file = new File(path);
    // file = new File( root_sd ) ;
    File list[] = file.listFiles();
    Log.i("DIR", "PATH" +file.getPath());
    for (int i = 0; i < list.length; i++) {
        // myList.add( list[i].getName() );
        File temp_file = new File(file.getAbsolutePath(),list[i].getName());
        Log.i("DIR", "PATH" +temp_file.getAbsolutePath());
        if (temp_file.isFile() && temp_file.listFiles() != null) {
            Log.i("inside", "call fn");
            listfiles(temp_file);

        } else {
            if (list[i].getName().toLowerCase().contains("pattern1"))
                Log.i("File", i + list[i].getName());
            if (list[i].getName().toLowerCase().contains("pattern2"))
                Log.i("File", i + list[i].getName());

        }
    }

Here only first level of search is happening . This condition if (temp_file.isFile() && temp_file.listFiles() != null)

is always returning false and thus recursive call not happening. Please help me to fix it. Thanks for your answer and time.

Was it helpful?

Solution

if the temp_file.isFile() returns true then it means it is a file and hence temp_file.listFiles() automatically becomes null thus making your entire statement false. Thus your combined statement returns a false always. What you need is a || in place of &&.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top