如何在Android 4.1.2上的外部存储公共目录文档中保存文件 [英] How to save files in External Storage Public Directory DOCUMENTS on Android 4.1.2
问题描述
我想在我的Android 4.1.2智能手机上将文件保存在documents目录中.
i want to save a file on my Android 4.1.2 smartphone in the documents directory.
此代码段:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"test.txt");
引发此异常:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoSuchFieldError: android.os.Environment.DIRECTORY_DOCUMENTS
这是可行的:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"test.txt");
但是我想将文件保存在我的文档目录中,而不是下载中.我已阅读过DIRECTORY_DOCUMENTS,仅在Android 4.4及更高版本中可用.但是我的智能手机上还有一个文档目录.因此,没有解决方案将其保存在文档中吗?
But i want to save my file in my documents directory, not in downloads. Ive read DIRECTORY_DOCUMENTS is only available in Android 4.4 and higher. But there is also a documents direcotry on my smartphone. So, is there no solution to save it in documents?
寻求答案
鹅卵石
推荐答案
您无法访问DIRECTORY_DOCUMENTS
,因为它在Android 4.1.2中不存在.这意味着,尽管您的外部存储中有一个Documents目录,但DIRECTORY_DOCUMENTS
并不指向该目录(因为它不存在).要解决此问题,必须创建目录(如果不存在)并手动获取该文件夹的路径.
You are not able to access DIRECTORY_DOCUMENTS
becuase it is not there in Android 4.1.2. Which means, though there is a Documents directory in your external storage, it is not pointed to by DIRECTORY_DOCUMENTS
(since it is non-existent). To solve this, you have to create the directory if it is not present and get the path to that folder manually.
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
boolean isPresent = true;
if (!docsFolder.exists()) {
isPresent = docsFolder.mkdir();
}
if (isPresent) {
File file = new File(docsFolder.getAbsolutePath(),"test.txt");
} else {
// Failure
}
这篇关于如何在Android 4.1.2上的外部存储公共目录文档中保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!