如何从我的Android应用程序获取资源目录列表?

如何从我的Android应用程序获取资源目录列表?

问题描述:

我的Android应用程序在资产目录中有一些文件,我想在启动时打开这些文件,方法是列出目录中的文件并打开每个文件。我试图使用AssetManager来做到这一点,但似乎并没有像我期望的那样做。我的示例代码如下。这是正确的方式还是有更好的方法来做到这一点?如何从我的Android应用程序获取资源目录列表?

,我使用下面的方法来打印出资产的目录树。

void displayFiles (AssetManager mgr, String path) { 
    try { 
     String list[] = mgr.list(path); 
     if (list != null) 
      for (int i=0; i<list.length; ++i) 
       { 
        Log.v("Assets:", path +"/"+ list[i]); 
        displayFiles(mgr, path + list[i]); 
       } 
    } catch (IOException e) { 
     Log.v("List error:", "can't list" + path); 
    } 

} 

从我活动的onCreate方法我执行以下操作:

final AssetManager mgr = getAssets();  
displayFiles(mgr, "/assets"); 
displayFiles(mgr, "./assets"); 
displayFiles(mgr, "/"); 
displayFiles(mgr, "./"); 

这给了我下面的输出

 
09-29 20:08:27.843: DEBUG/GFlash(6543): //AndroidManifest.xml 
09-29 20:08:27.954: DEBUG/GFlash(6543): //META-INF 
09-29 20:08:28.063: DEBUG/GFlash(6543): //assets 
09-29 20:08:28.233: DEBUG/GFlash(6543): //classes.dex 
09-29 20:08:28.383: DEBUG/GFlash(6543): //com 
09-29 20:08:28.533: DEBUG/GFlash(6543): //res 
09-29 20:08:28.683: DEBUG/GFlash(6543): //resources.arsc 

提前感谢!

约翰

呃。问题在于displayFiles方法,它缺少目录和文件名之间的分隔符“/”。对不起,如果我浪费了任何人的时间。下面是一个更正的displayFiles版本。

void displayFiles (AssetManager mgr, String path) { 
    try { 
     String list[] = mgr.list(path); 
     if (list != null) 
      for (int i=0; i<list.length; ++i) 
       { 
        Log.v("Assets:", path +"/"+ list[i]); 
        displayFiles(mgr, path + "/" + list[i]); 
       } 
    } catch (IOException e) { 
     Log.v("List error:", "can't list" + path); 
    } 

} 

约翰

+1

请注明您的问题作为回答。 – Matthias 2009-09-30 10:57:16

+1

我试过了。它告诉我,直到明天我才能接受我自己的答案。 – 2009-09-30 13:00:31

+2

这是显示根文件夹中的所有东西,但我实际上看不到我的资产文件夹中的任何文件,从而无法使用它? – schwiz 2010-10-07 03:19:58

要充分递归您可以更新方法如下:

void displayFiles (AssetManager mgr, String path, int level) { 

    Log.v(TAG,"enter displayFiles("+path+")"); 
    try { 
     String list[] = mgr.list(path); 
     Log.v(TAG,"L"+level+": list:"+ Arrays.asList(list)); 

     if (list != null) 
      for (int i=0; i<list.length; ++i) 
       { 
        if(level>=1){ 
         displayFiles(mgr, path + "/" + list[i], level+1); 
        }else{ 
         displayFiles(mgr, list[i], level+1); 
        } 
       } 
    } catch (IOException e) { 
     Log.v(TAG,"List error: can't list" + path); 
    } 

} 

然后调用具有:

final AssetManager mgr = applicationContext.getAssets(); 
displayFiles(mgr, "",0);