2016-03-07 90 views
4

因此,這裏是我的代碼:CreateTempFile在圖片文件夾中返回沒有這樣的文件或目錄?

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
String imageFileName = "JPEG_" + timeStamp + "_"; 
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
File image = File.createTempFile(
     imageFileName, /* prefix */ 
     ".jpg",   /* suffix */ 
     storageDir  /* directory */ 
); 

然而,我的應用程序間歇性地在File.createTempFile拋出錯誤:

java.io.IOException: open failed: ENOENT (No such file or directory). 

File文檔:

Parameters: 
prefix the prefix to the temp file name. 
suffix the suffix to the temp file name. 
directory the location to which the temp file is to be written, or null for the default location for temporary files, which is taken from the "java.io.tmpdir" system property. It may be necessary to set this property to an existing, writable directory for this method to work properly. 

Returns: 
the temporary file. 

Throws: 
IllegalArgumentException - if the length of prefix is less than 3. 
IOException - if an error occurs when writing the file. 

什麼的可能性無法寫入臨時文件?由於我指向外部存儲器,並且我的外部SD卡已插入設備內部。

+1

您是否在API 23(Marshmallow)設備上運行?您是否在運行時請求存儲權限? – ianhanniballake

+0

不,我正在使用4.1.2 JB設備。順便說一下,這個應用程序僅供內部使用,因此設備已定義,並且使用棒棒糖運行的設備沒有問題。 – Rendy

回答

0

getExternalStoragePublicDirectory()的Javadoc明確規定:

這個目錄可能還不存在,所以你必須使用它,例如與File.mkdirs()之前確保它存在 。

之後,我認爲你還應該檢查目錄是否存在。

+0

但我的設備有圖片文件夾,它存儲在內部SD卡中,而不是如我所料的那樣存儲在外部SD卡中。因此,該文件夾必須存在。 CMIIW。 – Rendy

+0

我想你可以用AOSP提交一個錯誤? –

+0

我不確定這是Android錯誤還是我的代碼錯誤(我確定它是正確的)。 – Rendy

相關問題