首先,我想说明一下
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在清单中指定,并检查environment.media_mounted。
在我看来,这真的很奇怪,因为它返回了true,但实际上并没有创建目录。
public static void downloadFiles(ArrayList<FileList> list) {
for (FileList file: list) {
try {
// This will be the download directory
File download = new File(downloadDirPatch.getCanonicalPath(), file.getPath());
// downloadDirPatch is defined as follows in a different class:
//
// private static String updateDir = "CognitionUpdate";
// private static File sdcard = Environment.getExternalStorageDirectory();
// final public static File downloadDir = new File(sdcard, updateDir);
// final public static File downloadDirPatch = new File(downloadDir, "patch");
// final public static File downloadDirFile = new File(downloadDir, "file");
if (DEV_MODE)
Log.i(TAG, "Download file: " + download.getCanonicalPath());
// Check if the directory already exists or not
if (!download.exists())
// The directory doesn't exist, so attempt to create it
if (download.mkdirs()) {
// Directory created successfully
Download.download(new URL(file.getUrl() + file.getPatch()), file.getPath(), file.getName(), true);
} else {
throw new ExternalStorageSetupFailedException("Download sub-directories could not be created");
}
else {
// Directory already exists
Download.download(new URL(file.getUrl() + file.getPatch()), file.getPath(), file.getName(), true);
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
} catch (ExternalStorageSetupFailedException essfe) {
essfe.printStackTrace();
}
}
}
“if(download.mkdirs())”返回true,但是当应用程序实际下载文件时,它抛出一个
FileNotFoundException: open failed: ENOENT (No such file or directory)
例外,当我在我的手机上检查目录之后,它就不存在了。
在程序的前面,应用程序设置了父下载目录,使用file.mkdir()可以正常工作,但是file.mkdirs()似乎不适合我。
最佳答案
您的问题并没有提供关于FileNotFoundException
的详细信息。检查触发此操作的路径。忘记您认为的路径是什么,记录它或通过调试器运行它,以查看它到底是什么。
根据未正确创建的目录,验证(用眼睛)路径是否确实是您认为的路径。我看到你已经在登录了,请检查一下你的日志。
最后,download.getCanonicalPath
真的在你认为的地方节省了东西吗?在调用之前,您正在使用Download.download
准备和验证一个目录,但是在调用download
时,您没有使用download
,因此无法判断。
顺便说一下,不要重复你自己,你可以重写而不必重复Download.download
行:
if (!download.exists())
if (!download.mkdirs()) {
throw new ExternalStorageSetupFailedException("Download sub-directories could not be created");
}
}
Download.download(new URL(file.getUrl() + file.getPatch()), file.getPath(), file.getName(), true);
关于java - 外部存储中的Android/Java File.mkdirs()无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16631560/