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.
Asked
Active
Viewed 1.1k times
4
3 Answers
20
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());

Peter Mortensen
- 30,738
- 21
- 105
- 131

Dheeraj Vepakomma
- 26,870
- 17
- 81
- 104
-
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. – biscuitstack Jul 11 '16 at 11:19
-
1@biscuitstack You can use an instance of an `Activity` or `Application` as the [`Context`](https://developer.android.com/reference/android/content/Context.html). – Dheeraj Vepakomma Jul 11 '16 at 13:18
-
This will need some more reading but you've given me a direction to go in, thanks Dheeraj. – biscuitstack Jul 11 '16 at 13:21
0
System.out.println
calls are really slow (well it's not really the function itself, but the underlying PrintStream which takes a lot of time to write text in the console).
Replace them by something else and it should be fine. For example, you can create and return an array with the file names.

Dalmas
- 26,409
- 9
- 67
- 80
0
If you prefer a non-recursive method you could try something like:
public void filetree (File directory)
{
List<File> dirlist = new ArrayList<File>(); // The list of directories to scan
dirlist.add(directory); // Initialize - with the stating point
do { // The scan list cannot start with zero entries - so bottom exit
File f = dirlist.remove(0); // Extract the directory to scan
if (f.listFiles() != null) // Check for permissions problems
for (File fl : f.listFiles())
if (fl.isDirectory()) dirlist.add(fl.getAbsoluteFile()); // directory - add to list
else Log.i ("msg", "File: " + fl.getAbsoluteFile()); // File - do something with it
} while (!dirlist.isEmpty()); // Continue until there is nothing left to scan
}

Peter Mortensen
- 30,738
- 21
- 105
- 131

ianeperson
- 41
- 2