How to recursively scan directories in Android

二次信任 提交于 2019-11-29 11:52:47

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());

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!