該代碼在大多數情況下都能正常工作,但有時會拋出異常。無法弄清楚是什麼原因造成的。爲什麼有時會拋出FileNotFoundException
什麼是確實是在
/storage/emulated/0/Download/theFileName.jpg
創建文件和寫入數據到它(從它的資源文件確實存在),但新創建的文件得到「文件不存在」異常。
(它確實在明顯有uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE", and uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE
「)
File sourceFile = new File(theSourceFileFullPath);
if (sourceFile.exists()) {
File downloadDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String downloadPath = downloadDirectory.getPath();
String newFilePath = (downloadPath + "/" + fileName);
File newFile = new File(newFilePath);
try {
FileInputStream in = new FileInputStream(sourceFile);
// ava.io.FileNotFoundException:
// /storage/emulated/0/Download/theFileName.jpg: open failed: ENOENT (No such file or directory)
// exception at this line
FileOutputStream out = new FileOutputStream(newFile);
//......
} catch (Exception e) {}
}
也許沒有完成它的創建,你嘗試訪問它。每次應用程序打開時,它都會嘗試創建一個文件並從中讀取它? –
嘗試替換:File newFile = new File(downlaodDirectory,fileName); – phongvan
Lispas,該應用程序已運行。 mdtuyen,File newFile = new File(downlaodDirectory,fileName);沒有幫助,並且如果同時具有downlaodDirectory和fileName,它與新文件(downlaodDirectory.getPath()+「/」+ fileName)相同; – lannyf