我试图将文件保存到“下载”文件夹。我得到目录并使用以下内容保存文件:
File exportDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, "filename.csv");
try {
if (file.exists()) {
// if the file exists create new file will do nothing. We want to
// overwrite contents every time
file.delete();
}
boolean created = file.createNewFile();
if (!created) {
Log.d("", "Failed to create file");
}
// .. write to file
MediaScannerConnection.scanFile(activity, new String[]{exportDir.getPath()}, null, null);
} catch (Exception sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
我已在三台设备上对此进行了测试:
在所有设备上,如果我导航到/ storage / sdcard0 / Download或类似的东西,我可以在那里看到我的文件。但是,如果我尝试打开本地"下载"应用程序我无法在Blu或Galaxy上看到该文件,但我可以在我的OnePlus 3上看到它。
我尝试重新启动手机以触发媒体扫描,并尝试使用MediaScannerConnection.scanFile
扫描文件和文件夹,但没有运气。根据FileManager,文件是-rw-rw----
,就像该文件夹中的大多数其他文件一样,这里发生了什么?
我的目标是将文件保存到逻辑位置,用户可以轻松找到该文件并将其从手机中取出。 Downloads文件夹是否有特殊规则?
任何建议都将不胜感激。
答案 0 :(得分:4)
“下载”文件夹是否有特殊规则?
外部存储上的#include <cstddef>
文件夹没有。下载应用程序。经典下载应用程序适用于通过Downloads/
下载的文件,但设备制造商可以根据需要对其进行修改。
我的目标是将文件保存到用户可以轻松找到并将其从手机中取出的逻辑位置。
DownloadManager
可能是也可能不是最佳位置 - 对于用户未明确从应用下载的内容,它不是我的首选。
答案 1 :(得分:-1)
确保tu定义权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
如果您使用的是Android 6.0+,则必须手动设置权限:
private void checkExternalStoragePermission() {
int permissionCheck = ContextCompat.checkSelfPermission(
this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
Log.i("Message", "OK.");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 225);
} else {
Log.i("Message", "PERMISSION NOT SET!");
}
}
您正在检查文件是否存在,但是您要删除文件!!!,此行不是必需的:
file.delete();
if (file.exists()) {
// if the file exists create new file will do nothing. We want to
// overwrite contents every time
//***This is the problem: file.delete();
Log.i("MainActivity", "File created and exists!");
}