How can I get a directory listing of resources from my Android app?

后端 未结 2 1045
深忆病人
深忆病人 2020-11-30 08:01

My Android application has some files in the assets directory that I want to open on startup by listing the files in the directory and opening each. I am trying to use the A

相关标签:
2条回答
  • 2020-11-30 08:46

    To be fully recursive you can update the method as following :

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

    Then call with :

    final AssetManager mgr = applicationContext.getAssets();
    displayFiles(mgr, "",0);     
    
    0 讨论(0)
  • 2020-11-30 09:04

    Ugh. The problem was in the displayFiles method, it was missing the separator, "/", between the directory and the filename. Sorry if I wasted anyone's time. A corrected version of displayFiles is below.

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

    John

    0 讨论(0)
提交回复
热议问题