Android學習筆記——儲存檔案(Saving Files)

來源:互聯網
上載者:User

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 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.