Android開發之assets文件夾中資源的獲取


assets中的文件都是保持原始的文件格式,需要使用AssetManager以字節流的形式讀取出來

步驟:

  • 1. 先在Activity里面調用getAssets() 來獲取AssetManager引用。
  • 2. 再用AssetManager的open(String fileName, int accessMode) 方法則指定讀取的文件以及訪問模式就能得到輸入流InputStream。
  • 3. 然后就是用已經open file 的inputStream讀取文件,讀取完成后記得inputStream.close() 。
  • 4.調用AssetManager.close() 關閉AssetManager。

需要注意的是,來自assets 中的文件只可以讀取而不能進行寫的操作

代碼:

 1  private void copyDataBase(String baseName) {
 2         OutputStream outputStream = null;
 3         InputStream inputStream = null;
 4         File file = new File(getFilesDir(), baseName);
 5         if ( file.exists() ) {
 6             return;
 7         }
 8         try {
 9             outputStream = new FileOutputStream(file);
10             inputStream = getAssets().open(baseName);
11             int len;
12             byte[] buffer = new byte[1024];
13             while ( (len = inputStream.read(buffer)) != -1 ) {
14                 outputStream.write(buffer, 0, len);
15             }
16         } catch ( IOException e ) {
17             e.printStackTrace();
18         } finally {
19             try {
20                 inputStream.close();
21                 outputStream.close();
22             } catch ( Exception e ) {
23                 e.printStackTrace();
24             }
25 
26         }
27     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM