简体   繁体   English

如何获取资产中某些文件夹中的文件数量?

[英]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. 结果在265个文件中它给我14秒。

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. AssetManager.list()太慢了。 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. 至少在我的情况下,由于assets文件夹是使用app构建的,因此我不会经常更改它。 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(); 所以它加载这个列表然后循环遍历列表而不必调用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. 它不漂亮或优雅,可能会破坏各种编码实践,但在我的情况下,它需要花费30秒到300毫秒的操作,所以在我的情况下这是值得的。

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. 如果您的assets文件夹发生了很大变化,手动更新列表会很麻烦,您可能会在构建过程中添加一个脚本,而不是在构建时自动为您创建此目录列表文件。

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. 通过使用AysncTask,您可以加快后台处理速度,而不是使用UI线程。 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. 它的主要用途是执行后台操作并在单独的线程中将结果发布到UI,但您仍然可以将它用于您的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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