AssetManager用於獲取assets下的資源。
1、getassets()得到AssetManager
2、AssetManager.close() 關閉AssetManager
3、Resources和Assets 中的文件只可以讀取而不能進行寫的操作。
4、AssetManager類常用方法:
返回指定路徑下的所有文件及目錄名: final String[] list(String path)
使用 ACCESS_STREAMING模式打開assets下的指定文件: final InputStream open(String fileName)
使用顯示的訪問模式打開assets下的指定文件: final InputStream open(String fileName, int accessMode)
訪問assets下的資源:
1、訪問assets下的網頁:
//實例化WebView對象 webview = new WebView(this); //加載需網頁 webview.loadUrl("file:///android_asset/index.html"); setContentView(webview);
注意:文件名字不能帶有空格和其他非法字符,只能英文字母大小、數字、下划線。
2、訪問圖片和文本文件
AssetManager asset=getAssets(); InputStream in=null; try { in=asset.open("images/logo.gif"); Bitmap bitmap=BitmapFactory.decodeStream(in); imageview1.setImageBitmap(bitmap); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { in=asset.open("test/test.txt"); ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer=new byte[1024]; int byteCount=0; while((byteCount=in.read(buffer))!=-1){ outSteam.write(buffer,0,byteCount); } byte[] buffer1=outSteam.toByteArray(); String str=new String(buffer1); Log.i("Test", str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
3、獲取assets的文件及目錄名:
// path為文件夾路徑 String fileNames[] =context.getAssets().list(path);