[英]How to get all files from assets folder
我正在嘗試使用以下代碼獲取我的資產文件夾中的所有圖像
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;
}
不知何故我不確定這個表達
File f=new File("file:///android_asset/");
好吧,我知道從資產文件夾中讀取 txt 文件或 html 文件時,您可以使用它,但是圖像也可以接受嗎?
我已經通過使用下面的代碼解決了這個問題
private List<String> getImage() throws IOException
{
AssetManager assetManager = getAssets();
String[] files = assetManager.list("image");
List<String> it=Arrays.asList(files);
return it;
}
萬一其他人想知道
通常,您可以使用AssetManager來管理您的資產文件夾中的文件。 在活動中,調用getAssets()方法獲取一個 AssetManager 實例。
編輯:您可以使用 AssetManager 來讀取這樣的圖像:
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();
}
請注意, BitmapFactory.decodeStream()
方法默認在 UI 線程上運行,因此如果圖像太大,應用程序會卡住。 在這種情況下,您可以更改樣本大小或啟動一個新線程來執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.