【发布时间】:2021-07-27 12:52:48
【问题描述】:
我无法使用 java 在我的 Android 11 设备中创建文件夹。我用了这段代码
File file = new File(Environment.getExternalStorageDirectory() + "/folderName/folderName1");
if (!file.mkdirs()) {
file.mkdirs();
}
String filePath = file.getAbsolutePath() + File.separator + "demoName";
Log.i("filePath",filePath.toString());
上述日志语句的输出是/storage/emulated/0/folderName/folderName1/demoName,但是当我检查我的手机时,并没有创建这样的文件夹。
只是为了确认我已经研究并确实包含了我需要包含在清单文件中的所有内容。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
我也放了
android:requestLegacyExternalStorage="true"
在应用程序标签内的正确位置。
这就是我从链接下载 PDF 的方法。
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/Aide Memoire");
public void DownloadBooks(String url,String title){
DownloadManager.Request request=new DownloadManager.Request(Uri.parse(url));
String tempTitle=title.trim();
request.setTitle(tempTitle);
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB){
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
String filePath = file.getAbsolutePath();
Log.i("filePath",filePath.toString());
request.setDestinationInExternalPublicDir(filePath,tempTitle+".pdf");
Toast.makeText(this, "Saved to " + filePath , Toast.LENGTH_SHORT).show();
DownloadManager downloadManager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
request.setMimeType("application/pdf");
request.allowScanningByMediaScanner();
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
downloadManager.enqueue(request);
}
DownloadBooks("a link"," a name for the file");
运行上述内容后,我得到一个错误,logcat 说
java.lang.IllegalStateException: Not one of standard directories:
现在,如何在 Android 11 的 Internal Storage 中创建自定义文件夹而不出错?
【问题讨论】:
-
请求旧版外部存储仅适用于 Android 10 设备。
-
request.setDestinationInExternalPublicDir(filePath,tempTitle+".pdf")不要乱用 File 类路径。request.setDestinationInExternalPublicDir(Environment.DIRECTORY.DOCUMENTS,tempTitle+".pdf"). -
或
request.setDestinationInExternalPublicDir(Environment.DIRECTORY.DOCUMENTS, "Aide Memoire/" +tempTitle+".pdf")。 -
那么,这是否表明文件(主要是文档)只能下载到 DOCUMENTS 文件夹中,而不能下载到 DOCUMENTS 文件夹内的嵌套文件夹中?
-
你为什么要问?你没看到我也用了“Aide Memoires”吗?你没有尝试所有吗?如果它有效,你为什么不报告?
标签: java android directory android-file