2017-05-05 116 views
0

我想給我的應用程序的用戶選擇保存到內部手機存儲器或SD卡。如果我創建了用戶的選擇一個File的URI(不帶文件名)是一樣的東西:寫入SD卡Android

內部:內容:/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')。

+0

創建文件時,你混合兩個概念,你發送'content' URI而它需要一個'file' URI,更多信息在https://developer.android.com/reference/java/io/File.html從'Environment.getExternalStorageDirectory()'返回的路徑是正確的,AVD通常模擬一個外部存儲在這個路徑中,不要將SD卡與外部存儲混淆,它可以是不同的來源,更多信息請參閱https://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory() –

+0

@AlbertoMéndez感謝您的信息。我知道「外部」存儲可能是SD卡或可安裝的設備內存,但是如何寫入SD卡而不是設備內存? – petehallw

回答

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); 
} 
+0

這是我今天看到的最大的廢話。 – greenapps

+0

@greenapps是什麼意思? – redAllocator

+0

你贏了價格;-)。 – greenapps

0

因爲路徑是不同的設備不同,您收到此錯誤。

嘗試使用Environment.getExternalStorageDirectory()writePath

請記住在android系統6及以上的,你必須在運行時請求權限

+0

但正如我在我的文章中提到的,這總是寫入設備的內部存儲而不是SD卡。 – petehallw