android - Android MediaStore - 存储 zip 文件并作为文件打开
问题描述
早上好,
我在 Android 11 上遇到了 MediaStore 的问题。我必须下载 .zip 文件,然后打开它并获取文件 uri 和路径。
这是保存文件的代码并且可以正常工作。我可以找到文件。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
imageCollection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "application/zip");
contentValues.put(MediaStore.MediaColumns.SIZE, lengthOfFile);
Uri uri = context.getContentResolver().insert(MediaStore.Files.getContentUri("external"), contentValues);
OutputStream outputStream = context.getContentResolver().openOutputStream(uri);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
input.close();
}
但我以后无法打开此文件。
val collection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Files.getContentUri("external")
} else {
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
}
val projection = arrayOf(
MediaStore.Files.FileColumns.RELATIVE_PATH,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.SIZE,
MediaStore.Files.FileColumns._ID
)
val cursor = requireContext().contentResolver.query(collection, projection, null, null, null)
if (cursor!!.getCount() == 0) {
Log.d(TAG, "No file")
} else {
val idColumn=cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID)
val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME)
val pathColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.RELATIVE_PATH)
while (cursor!!.moveToNext()) {
val id = cursor.getLong(idColumn)
val name = cursor.getString(nameColumn)
val path = cursor.getString(pathColumn)
if (name == "2.1.2.zip") {
val contentUri: Uri = MediaStore.Files.getContentUri("external")
val file= File("content://media/external/file/2.1.2.zip")
if (file.exists()) {
Log.d(TAG, "File not exist")
} else {
Log.d(TAG, "Error")
}
路径值返回:下载/
名称值返回:2.1.2.zip
MediaStore.Files.getContentUri("external"): content://media/external/file
知道如何访问该文件吗?我尝试了很多不同的方式来获取文件,但总是得到“文件不存在”。
解决方案
推荐阅读
- java - 为什么 Map 接口中有一个 'remove(key, value)' 方法?
- excel - VLOOKUP 从另一个工作表中获取数据
- php - 在结帐页面上更改 WooCommerce 优惠券的“删除”链接文本
- c - 在 C 中输入矩阵元素的总和
- javascript - Socket.io 踢特定用户
- c# - 我如何制作一个计时器来改变他在不同场合运行的滴答数?
- java - Java Runtime.getRuntime exec 复制失败
- javascript - 我想隐藏所有带有标签的元素并包含一个链接
- assembly - 为什么 lea 显然将随机地址移动到 rdi?
- html - 仅当标签文本可用时添加星号