【问题标题】:List of files in assets folder and its subfoldersassets文件夹及其子文件夹中的文件列表
【发布时间】:2013-04-26 10:43:29
【问题描述】:

我的 Android 项目的“assets”文件夹中有一些包含 HTML 文件的文件夹。我需要在列表中显示资产子文件夹中的这些 HTML 文件。我已经写了一些关于制作这个列表的代码。

lv1 = (ListView) findViewById(R.id.listView);
// Insert array in ListView

// In the next row I need to insert an array of strings of file names
// so please, tell me, how to get this array

lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, filel));
lv1.setTextFilterEnabled(true);
// onclick items in ListView:
lv1.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        //Clicked item position
        String itemname = new Integer(position).toString();  
        Intent intent = new Intent();
        intent.setClass(DrugList.this, Web.class);
        Bundle b = new Bundle();
        //I don't know what it's doing here
        b.putString("defStrID", itemname); 
        intent.putExtras(b);
        //start Intent
        startActivity(intent);
    }
});

【问题讨论】:

    标签: android assets


    【解决方案1】:
    private boolean listAssetFiles(String path) {
    
        String [] list;
        try {
            list = getAssets().list(path);
            if (list.length > 0) {
                // This is a folder
                for (String file : list) {
                    if (!listAssetFiles(path + "/" + file))
                        return false;
                    else {
                        // This is a file
                        // TODO: add file name to an array list
                    }
                }
            } 
        } catch (IOException e) {
            return false;
        }
    
        return true; 
    } 
    

    使用资产文件夹的根文件夹名称调用 listAssetFiles。

        listAssetFiles("root_folder_name_in_assets");
    

    如果根文件夹是资产文件夹,则使用

    调用它
        listAssetFiles("");    
    

    【讨论】:

    • 如果您是从活动或服务中执行此操作,则 mContext = getApplicationContext();或 mContext = ActivityName.this;你也可以丢弃它。
    • 在java中使用StringBuilder不要连接String
    • 将假定空的子目录是文件
    • 是的,但为什么要把空文件夹放在资产中?
    • @Motasharred :现在已经很久了......但是上面的 sn-p 中的 else 缺少一个 }
    【解决方案2】:

    试试这个,它会在你的情况下工作

    f = getAssets().list("");
    for(String f1 : f){
        Log.v("names",f1);
    }
    

    上面的sn-p会显示资产根目录的内容。

    例如……如果下面是资产结构……

    assets
     |__Dir1
     |__Dir2
     |__File1
    

    Snippet 的输出将是 .... 目录 1 目录 2 文件 1

    如果需要Directory Dir1的内容

    在列表函数中传递目录的名称。

      f = getAssets().list("Dir1");
    

    【讨论】:

    • 我编辑了这段代码,因为 Eclipse 显示错误。 String[] f = null; try { f = getAssets().list(""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(String f1:f){ Log.v("names",f1); } 这个
    • 结果 - 模拟器显示了 4 个项目列表:药物、图像、声音、webkit
    • 是的,它表明..但是在asset中传递youtlr目录的名称可以帮助你摆脱它在括号内传递你的父文件夹,它的所有内容都将被列出......比如 getAssets().list("drugs");
    • 您需要重复相同的过程来处理资产文件夹内每个文件夹中的文件...而不是创建一个具有文件夹名称的字符串数组并在列表函数中继续传递它们
    【解决方案3】:

    希望得到帮助:

    以下代码会将所有文件夹及其内容和子文件夹的内容复制到 sdcard 位置:

     private void getAssetAppFolder(String dir) throws Exception{
    
        {
            File f = new File(sdcardLocation + "/" + dir);
            if (!f.exists() || !f.isDirectory())
                f.mkdirs();
        }
         AssetManager am=getAssets();
    
         String [] aplist=am.list(dir);
    
         for(String strf:aplist){
            try{
                 InputStream is=am.open(dir+"/"+strf);
                 copyToDisk(dir,strf,is);
             }catch(Exception ex){
    
    
                getAssetAppFolder(dir+"/"+strf);
             }
         }
    
    
    
     }
    
    
     public void copyToDisk(String dir,String name,InputStream is) throws IOException{
         int size;
            byte[] buffer = new byte[2048];
    
            FileOutputStream fout = new FileOutputStream(sdcardLocation +"/"+dir+"/" +name);
            BufferedOutputStream bufferOut = new BufferedOutputStream(fout, buffer.length);
    
            while ((size = is.read(buffer, 0, buffer.length)) != -1) {
                bufferOut.write(buffer, 0, size);
            }
            bufferOut.flush();
            bufferOut.close();
            is.close();
            fout.close();
     }
    

    【讨论】:

      【解决方案4】:

      这是我的问题的解决方案,我发现 100% 列出所有目录和文件,甚至子目录和子目录中的文件。

      注意:就我而言

      1. 文件名有一个 .在他们之中。即 .htm .txt 等
      2. 目录名称没有任何 .在他们里面。

        listAssetFiles2(path); // <<-- Call function where required
        
        
        //function to list files and directories
        public void listAssetFiles2 (String path){
        String [] list;
        
        try {
            list = getAssets().list(path);
            if(list.length > 0){
                for(String file : list){
                    System.out.println("File path = "+file);
        
                    if(file.indexOf(".") < 0) { // <<-- check if filename has a . then it is a file - hopefully directory names dont have . 
                        System.out.println("This is a folder = "+path+"/"+file);
                        listAssetFiles2(file); // <<-- To get subdirectory files and directories list and check 
                    }else{
                        System.out.println("This is a file = "+path+"/"+file);
                    }
                }
        
            }else{
                System.out.println("Failed Path = "+path);
                System.out.println("Check path again.");
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        }//now completed
        

      谢谢

      【讨论】:

        【解决方案5】:

        基于@Kammaar 的回答。这个 kotlin 代码扫描文件树的叶子:

        private fun listAssetFiles(path: String, context: Context): List<String> {
            val result = ArrayList<String>()
            context.assets.list(path).forEach { file ->
                val innerFiles = listAssetFiles("$path/$file", context)
                if (!innerFiles.isEmpty()) {
                    result.addAll(innerFiles)
                } else {
                    // it can be an empty folder or file you don't like, you can check it here
                    result.add("$path/$file")
                }
            }
            return result
        }
        

        【讨论】:

          【解决方案6】:

          我认为最好检查文件是否为dir,替代尝试,catch!

           public static  List<String> listAssetFiles(Context c,String rootPath) {
              List<String> files =new ArrayList<>();
              try {
                  String [] Paths = c.getAssets().list(rootPath);
                  if (Paths.length > 0) {
                      // This is a folder
                      for (String file : Paths) {
                          String path = rootPath + "/" + file;
                          if (new File(path).isDirectory())
                              files.addAll(listAssetFiles(c,path));
                          else files.add(path);
                      }
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
             return files;
          }
          

          【讨论】:

            【解决方案7】:

            此方法返回 Assets 文件夹中目录中的文件名

             private fun getListOfFilesFromAsset(path: String, context: Context): ArrayList<String> {
                        val listOfAudioFiles = ArrayList<String>()
                        context.assets.list(path)?.forEach { file ->
                            val innerFiles = getListOfFilesFromAsset("$path/$file", context)
                            if (innerFiles.isNotEmpty()) {
                                listOfAudioFiles.addAll(innerFiles)
                            } else {
                                // it can be an empty folder or file you don't like, you can check it here
                                listOfAudioFiles.add("$path/$file")
                            }
                        }
                        return listOfAudioFiles
                    }
            

            例如你想从声音文件夹加载音乐文件路径

            您可以像这样获取所有声音:

              private const val SOUND_DIRECTORY = "sound"
            
            
               fun fetchSongsFromAssets(context: Context): ArrayList<String> {
                    return getListOfFilesFromAsset(SOUND_DIRECTORY, context)
                }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-05-08
              • 2019-06-19
              • 1970-01-01
              • 1970-01-01
              • 2016-07-24
              • 2019-01-02
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多