简体   繁体   中英

How to get an amount of the files in certain folder in assets?

My method is too slow. The result in 265 files it gives me in 14 seconds.

Method :

private void assetFilesAmount(String path) {
    AssetManager assetManager = getAssets();
    String assets[] = null;
    try {
        assets = assetManager.list(path);
        if (assets.length == 0) {
            filesAmount++;              
        } else {
            for (int i = 0; i < assets.length; ++i) {
                assetFilesAmount(path + "/" + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}

I ran into the same problem recently (I wanted to copy some files from the assets directory), and it was in a place in the app where a several second wait was just not going to cut it. AssetManager.list() is just too slow. So I came up with a solution, it is ugly but it is fast.

At least in my case, since the assets folder is built with the app, I am not changing it often. So the solution I came up with was to include a file in the assets directory that listed all of the files in the assets. For example:

somedir/somefile.txt
somedir/anotherdir/anotherfile.txt
somedir/anotherdir/yetanotherfile.txt
somedir/anotherdir/somanyfiles.txt
...

So it loads this list and then loops through the list rather than having to call AssetManager.list();

It ain't pretty or graceful, and probably breaks all sorts of coding practices but in my case it took an operation from taking 30 seconds to 300 milliseconds, so it was worth it in my case.

If your assets folder is changing a lot, and it would be a pain to manually update the list, you could probably put a script into your build process than would make this directory listing file automatically for you on build.

Have you possibly thought about using a separate thread for this procedure? by using AysncTask you can potentially speed up your background processing and not make use of the UI thread. Its main use is for performing background operations and publishing the results to the UI in a separate thread, but you can still make use of it for your purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM