若想要在程式啟動時,將檔案預載至SD卡中,該如何實做呢?
Step 1: 建立assets資料夾
在專案main 目錄下(專案名稱/module name/src/main),建立assets資料夾,並將預先載入的檔案放到此目錄中。
Step 2: 取得AssetManager
使用Contex.getAssets() 的方式可取得AssetManager
Step 3: 取得檔案流
再使用AssetManager.open(檔案名稱)的方式取得InputStream
AssetManager.open(“photo.jpg”);
若檔案在assets的子目錄中時,需要將子目錄名稱帶入
1
| AssetManager.open("picture/photo.jpg");
|
Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| private void copyAssetFile() { InputStream is = null; FileOutputStream fos = null; try { File sdFile = new File("/mnt/sdcard/sd_photo.jpg");
if (!sdFile.exists()) { sdFile.createNewFile(); }
is = context.getAssets().open("picture/photo.jpg"); fos = new FileOutputStream(sdFile);
byte[] buffer = new byte[2048]; int byteCount = 0; while ((byteCount = is.read(buffer)) != -1) { fos.write(buffer, 0, byteCount); } fos.flush(); } catch (IOException e) { } finally { closeQuietly(is); closeQuietly(fos); } }
private void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException ex) { } } }
|