-->

How to get all files from assets folder

2020-08-09 10:03发布

问题:

I am trying to get all images in my assets folder using the codes below

private List<String> getImage()
      {
        /* 设定目前所在路径 */
        List<String> it=new ArrayList<String>();      
        File f=new File("file:///android_asset/");  
        File[] files=f.listFiles();
        Log.d("tag", "读取asset资源");

        /* 将所有文件存入ArrayList中 */
        for(int i=0;i<files.length;i++)
        {
          File file=files[i];
          if(getImageFile(file.getPath()))
            it.add(file.getPath());
        }
        return it;

      }

      private boolean getImageFile(String fName)
      {
        boolean re;

        /* 取得扩展名 */
        String end=fName.substring(fName.lastIndexOf(".")+1,
                      fName.length()).toLowerCase(); 

        /* 按扩展名的类型决定MimeType */
        if(end.equals("jpg")||end.equals("gif")||end.equals("png")
                ||end.equals("jpeg")||end.equals("bmp"))
        {
          re=true;
        }
        else
        {
          re=false;
        }
        return re; 
      }

somehow I am not sure about this expression

File f=new File("file:///android_asset/"); 

Well, I know that when read a txt file or html file from assets folder you can use this,but would images accept this too?

I have resolve this problem by using the code below

private List<String> getImage() throws IOException
      {
        AssetManager assetManager = getAssets();
        String[] files = assetManager.list("image");   
        List<String> it=Arrays.asList(files);
        return it; 

        }

in case somebody else want to know

回答1:

In general, you can use the AssetManager to manage files in your asset folder. In the activity, call getAssets () method to get an AssetManager Instance.

EDIT: you can use the AssetManager to read images like this:

AssetManager am=this.getAssets();
        try {
            Bitmap bmp=BitmapFactory.decodeStream(am.open("009.gif"));
            chosenImageView.setImageBitmap(bmp);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Note that the BitmapFactory.decodeStream() method runs on UI thread by default, so the app would get stuck if the image is too large. In that case, you can change the samplesize or start a new thread to do this.