How to get the number of files in a specific folder in assets?

My method is too slow. The result is in 265 files, which 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); } } 
+4
source share
2 answers

I ran into the same problem recently (I wanted to copy some files from the resource directory), and this was in the application location, where for a few seconds the wait was simply not going to cut it. AssetManager.list () is too slow. So I came up with a solution, it is ugly, but it is fast.

At least in my case, since the resource folder is created using the application, I do not often change it. Therefore, the solution I came up with was to include the file in the asset directory, which lists all the files in the assets. For instance:

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

Therefore, it loads this list and then iterates over the list, rather than calling AssetManager.list ();

This is ugly or elegant, and probably violates all kinds of encoding methods, but in my case it took from 30 seconds to 300 milliseconds, so in my case it was worth it.

If your resource folder changes a lot and it would be painful to manually update the list, you could probably add a script to your build process, which would automatically create this directory file for you during the build.

+4
source

Did you think of using a separate thread for this procedure? using AysncTask , you can speed up your background processing and not use the user interface thread. Its main purpose is to perform background operations and publish the results in the user interface in a separate thread, but you can still use it for your own purposes.

0
source

Source: https://habr.com/ru/post/1379906/


All Articles