我正在尝试将文件保存到下载文件夹。我获取了目录并使用以下方式保存文件:
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);
}
我已经在三台设备上测试过了:
- OnePlus 3(Android 8.0.0)
- Blu Advance 5.0(Android 5.1)
- Samsung Galaxy S3(Android 4.4.4)
我已经尝试重新启动手机来触发媒体扫描,并尝试使用 MediaScannerConnection.scanFile 扫描文件和文件夹,但没有成功。根据 FileManager,该文件与该文件夹中的大多数其他文件一样为 -rw-rw----,那么这里到底发生了什么?
我的目标是将文件保存到一个逻辑位置,用户可以轻松找到并从其手机中取出。下载文件夹有特殊规则吗?
欢迎提出任何建议。