標籤:android raw assets
res/raw和assets的相同點:
1.兩者目錄下的檔案在打包後會原封不動的儲存在apk包中,不會被編譯成二進位。
res/raw和assets的不同點:
1.res/raw中的檔案會被映射到R.java檔案中,訪問的時候直接使用資源ID即R.id.filename;assets檔案夾下的檔案不會被映射到R.java中,訪問的時候需要AssetManager類。
2.res/raw不可以有目錄結構,而assets則可以有目錄結構,也就是assets目錄下可以再建立檔案夾
*讀取檔案資源:
1.讀取res/raw下的檔案資源,通過以下方式擷取輸入資料流來進行寫操作
- InputStream is = getResources().openRawResource(R.id.filename);
2.讀取assets下的檔案資源,通過以下方式擷取輸入資料流來進行寫操作
- AssetManager am = null;
- am = getAssets();
- InputStream is = am.open("filename");
assets檔案夾裡面的檔案都是保持原始的檔案格式,需要用AssetManager以位元組流的形式讀取檔案。 1. 先在Activity裡面調用getAssets() 來擷取AssetManager引用。 2. 再用AssetManager的open(String fileName, int accessMode) 方法則指定讀取的檔案以及訪問模式就能得到輸入資料流InputStream。 3. 然後就是用已經open file 的inputStream讀取檔案,讀取完成後記得inputStream.close() 。 4.調用AssetManager.close() 關閉AssetManager。
需要注意的是,來自Resources和Assets 中的檔案只可以讀取而不能進行寫的操作
以下為Assets檔案中讀取:
public class ReadAsset extends Activity{ @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.read_asset); try { InputStream is = getAssets().open("read_asset.txt");//檔案夾下的一個二進位檔案 int size = is.available(); // Read the entire asset into a local byte buffer. byte[] buffer = new byte[size]; is.read(buffer); is.close(); // Convert the buffer into a string. String text = new String(buffer); // Finally stick the string into the text view. TextView tv = (TextView)findViewById(R.id.text); tv.setText(text); } catch (IOException e) { // Should never happen! throw new RuntimeException(e); } }}以下為從Raw檔案中讀取:
public String getFromRaw(){ try { InputStreamReader inputReader = new InputStreamReader( getResources().openRawResource(R.raw.test1)); BufferedReader bufReader = new BufferedReader(inputReader); String line=""; String Result=""; while((line = bufReader.readLine()) != null) Result += line; return Result; } catch (Exception e) { e.printStackTrace(); } }