How to recursively scan directories in Android

10,201

You should almost always access the file system only from a non-UI thread. Otherwise you risk blocking the UI thread for long periods and getting an ANR. Run the FileWalker in an AsyncTask's doInBackground().

This is a slightly optimized version of FileWalker:

public class Filewalker {

    public void walk(File root) {

        File[] list = root.listFiles();

        for (File f : list) {
            if (f.isDirectory()) {
                Log.d("", "Dir: " + f.getAbsoluteFile());
                walk(f);
            }
            else {
                Log.d("", "File: " + f.getAbsoluteFile());
            }
        }
    }   
}

You can invoke it from a background thread like this:

Filewalker fw = new Filewalker();
fw.walk(context.getFilesDir());
Share:
10,201
Admin
Author by

Admin

Updated on July 10, 2022

Comments

  • Admin
    Admin almost 2 years

    How can I recursively scan directories in Android and display file name(s)? I'm trying to scan, but it's slow (force close or wait). I'm using the FileWalker class given in a separate answer to this question.

  • biscuitstack
    biscuitstack almost 8 years
    Forgive my naive question but how is context being assigned here? I typically pass it through from an activity as an argument to a function but I see no arguments here? Without, context is giving me a 'cannot resolve' compile error.
  • Dheeraj Vepakomma
    Dheeraj Vepakomma almost 8 years
    @biscuitstack You can use an instance of an Activity or Application as the Context.
  • biscuitstack
    biscuitstack almost 8 years
    This will need some more reading but you've given me a direction to go in, thanks Dheeraj.