【问题标题】:Save an image to Shared Storage. Problem if the image exists with the same name将图像保存到共享存储。如果图像存在同名的问题
【发布时间】:2021-10-21 18:49:53
【问题描述】:

我想将图像保存到Shared Storage,适用于 Android 10 或更高版本,并告诉用户文件名。

ContentResolver cr = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put( MediaStore.MediaColumns.DISPLAY_NAME, file_name );
contentValues.put( MediaStore.MediaColumns.MIME_TYPE, "image/png");
contentValues.put( MediaStore.MediaColumns.RELATIVE_PATH, 
Environment.DIRECTORY_PICTURES+"/"+context.getString( R.string.app_name ));

uri = cr.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
out = cr.openOutputStream(uri);
// and write a bitmap by compress method

它工作正常。但是如果存在同名的图像,例如“image.png”,那么系统会创建文件名“image (1).png”、“image (2).png”等。 如何获得真实的文件名? 还有一个。如何获取图像文件大小以获取信息。我现在使用这个,但不确定这是正确的做法。

AssetFileDescriptor afd = context.getContentResolver().openAssetFileDescriptor(uri , "r");
info_out.size = afd.getLength();
afd.close();

【问题讨论】:

  • 使用DocumentFile 作为显示名称和长度。
  • 先检查文件是否已经存在。如果是这样,如果你想覆盖文件,请使用它的 uri。
  • @blackapps 我无法检查,我还没有 uri。
  • 检查:您应该在媒体存储中查询该文件名和相对路径。如果您获得 uri,则该文件存在。否则不会。

标签: android android-contentresolver


【解决方案1】:

使用光标获取文件名并检查它是否存在。检查以下代码:

           Cursor returnCursor =
    getContentResolver().query(uri, null, null, null, null);
    int nameIndex = returnCursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
    do{ 
   String path=cursor.getString(nameIndex);
   File file=new File(path);
if(file.exists())
 {
 //your logic here
  }

   }while(returnCursor.moveToFirst());

 

【讨论】:

  • 我还没有 Uri。 Insert 方法返回 uri。
  • @blackapps 感谢您指出我的错误。我已尝试使用此方法获取文件名,它确实有效。您能否简要介绍一下为什么此代码不起作用?
  • 你得到文件名。但是您不能使用 File 类来查看文件名是否存在。您的查询可以提供数以千计的名称。你要对他们做什么?废话代码。如果您获得文件名,则该文件正常存在。那你就不用再检查了。
猜你喜欢
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多