Android學習筆記——儲存檔案(Saving Files)
Android裝置有兩種檔案儲存體地區: 內部儲存和外部儲存 ("internal" and "external" storage)。 這名字來自早期Android,那時大多數Android裝置提供兩種儲存方式:內建的非易失的記憶體(內部儲存)和可移動的儲存例如micro SD卡(外部儲存)。 一些裝置將永久記憶體分為內部和外部兩部分,因此即使沒有外部儲存,依舊有兩種儲存空間。不管有沒有外部儲存,API的方法都是一樣的。 內部儲存: 始終都是可用的 儲存的檔案只能被你的app以預設的方式訪問 卸載app,系統從內部儲存中刪除你app的所有檔案 內部儲存適用於你不想使用者或其他app訪問你的檔案 外部儲存:不總是可用的(使用者可能將外部儲存以USB方式串連, 一些情況下會從裝置中移除)是全域可讀的(world-readable),因此一些檔案可能不受控制地被讀取卸載app,只刪除你儲存在getExternalFilesDir()目錄下的檔案 外部儲存適用於不需要儲存限制的檔案以及你想要與其他app共用的檔案或者是允許使用者用電腦訪問的檔案 app預設安裝在內部儲存中,通過指定android:installLocation 屬性值可以讓app安裝在外部儲存中。 擷取外部儲存許可權: 讀與寫:<manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ...</manifest> 讀:<manifest ...> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ...</manifest> 在內部儲存儲存檔案不需要任何許可權,你的app在內部儲存中總是有讀寫權限。 在內部儲存中儲存檔案:擷取適當的目錄: getFilesDir() app檔案在內部儲存中的目錄eg: File file = new File(context.getFilesDir(), filename); getCacheDir() app臨時快取檔案在內部儲存中的目錄 調用openFileOutput()擷取FileOutputStream寫入檔案到內部目錄eg:複製代碼 1 String filename = "myfile"; 2 String string = "Hello world!"; 3 FileOutputStream outputStream; 4 5 try { 6 outputStream = openFileOutput(filename, Context.MODE_PRIVATE); 7 outputStream.write(string.getBytes()); 8 outputStream.close(); 9 } catch (Exception e) {10 e.printStackTrace();11 }複製代碼 調用 createTempFile()緩衝一些檔案:複製代碼 1 public File getTempFile(Context context, String url) { 2 File file; 3 try { 4 String fileName = Uri.parse(url).getLastPathSegment(); 5 file = File.createTempFile(fileName, null, context.getCacheDir()); 6 catch (IOException e) { 7 // Error while creating file 8 } 9 return file;10 }