[英]Write to SD card Android
我想讓我的應用程序用戶可以選擇保存到手機內部存儲器或SD卡中。 如果我根據用戶的選擇創建File
,則URI(無文件名)類似於:
內部:內容:/com.android.externalstorage.documents/tree/primary%3A
SD:內容:/com.android.externalstorage.documents/tree/760E-F734%3A
但是,如果嘗試使用以下代碼將文件寫入這些目錄,則會出現錯誤java.io.IOException: No such file or directory
:
File writePath = new File("content:/com.android.externalstorage.documents/tree/primary%3A")
File file = new File(writePath, fileName);
try {
file.createNewFile();
} catch (IOException e) {
Log.e("saveSurvey", "Failed to create file!" + e.getMessage());
return false;
}
因此,該文件將被寫入如下位置:
內容:/com.android.externalstorage.documents/tree/primary%3A/ [我的文件名]
我已經在清單中聲明了WRITE_EXTERNAL_STORAGE
權限,因此我想這不是權限問題,而更多是無效路徑問題。
如果這些不是有效的文件路徑,我該如何寫SD卡? 使用Environment.getExternalStorageDirectory()
始終寫入設備的內部存儲(“ / storage / emulated / 0”)。
請檢查您的文件路徑。 調用getAbsolutePath()函數並檢查writePath
File writePath = new File("content:/com.android.externalstorage.documents/tree/primary%3A")
if(writePath.exists() && writePath.isDirectory()) {
//File extensions can be declared
File file = new File(writePath.getAbsolutePath(), fileName+ extensions);
}
由於路徑在不同的設備中不同,您會收到此錯誤。
嘗試使用Environment.getExternalStorageDirectory()
作為writePath
請記住,在Android 6及更高版本中,您必須在運行時請求權限
File
僅適用於文件系統路徑或file://
URI,並且您在此處具有content://
URI。 (此外,要從URI創建文件,您可以將其作為Uri
而不是字符串進行傳遞。)
根據您要對該文件進行的操作, DocumentFile
可能會為您工作。 它旨在提供類似於File
的界面,但圍繞Storage Access Framework構建。 您可以獲取以這種方式創建的文件的輸入和輸出流,並執行一些基本的文件操作。
一件令人痛苦的事情是涉及標准Java庫的任何事情都需要File
參數,因為沒有正式的方法可以從content://
URI到實際的File
實例,除了可能在下一次更新,或在尚未考慮的一台設備上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.