Android中怎么讀寫assets目錄中的資源文件,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
一、AssetManager讀取文件常用的幾個API
1.文件讀取方式
AssetManager.open(String filename),返回的是一個InputSteam類型的字節流,這里的filename必須是文件,而不能是文件夾,AssetManager打開 資源文件的open方法是一個重載方法,可以添加一個打開方式的int參數,根據參數不同可做相應操作。具體請看官方文檔http://web.mit.edu/clio/MacData/afs/sipb/project/android/docs/reference/android/content/res/AssetManager.html
2.資源文件是可以存在文件夾以及子目錄
public final String[]list(String path),返回當前目錄下面的所有文件以及子目錄的名稱??梢酝ㄟ^遞歸遍歷整個文件目錄,實現所有資源文件的訪問。String[] Array of strings, one for each asset. These file names are relative to 'path'. You can open the file by concatenating 'path' and a name in the returned string (via File) and passing that to open().
二、相關實現代碼
資源APK(A.apk)

具體實現代碼片段,由于使用系統權限,生成的路徑可以自己改一下B.apk
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { ctxDealFile = this.createPackageContext("com.zlc.ipanel", Context.CONTEXT_IGNORE_SECURITY); } catch (NameNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } btn3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { String uiFileName = "ipanelJoin"; deepFile(ctxDealFile, uiFileName); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); textView.setText("file is wrong"); } } }); // } public void deepFile(Context ctxDealFile, String path) { try { String str[] = ctxDealFile.getAssets().list(path); if (str.length > 0) {//如果是目錄 File file = new File("/data/" + path); file.mkdirs(); for (String string : str) { path = path + "/" + string; System.out.println("zhoulc:\t" + path); // textView.setText(textView.getText()+"\t"+path+"\t"); deepFile(ctxDealFile, path); path = path.substring(0, path.lastIndexOf('/')); } } else {//如果是文件 InputStream is = ctxDealFile.getAssets().open(path); FileOutputStream fos = new FileOutputStream(new File("/data/" + path)); byte[] buffer = new byte[1024]; int count = 0; while (true) { count++; int len = is.read(buffer); if (len == -1) { break; } fos.write(buffer, 0, len); } is.close(); fos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。