本文介绍了如何从Android Oreo(8.1)或更高版本中的URI获取文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

预期的行为

当我选择存储在下载中的文件时,它应该能够检索其文件名并路径

When I am selecting the file which is stored inside "Download", it should able to retrieves its file name and path

实际行为

当我选择存储在其中的文件时下载,它返回null。

When I am selecting the file which is stored inside "Download", it returns null.

重现问题的步骤


  1. 调用选择方法时,它将显示Android中的文件夹

  2. 转到下载位置,选择一个文件

  3. 它从URI获取真实路径时返回null





public static String getPath(final Context context, final Uri uri) {
   String id = DocumentsContract.getDocumentId(uri);
   if (!TextUtils.isEmpty(id)) {
      if (id.startsWith("raw:")) {
          return id.replaceFirst("raw:", "");
      }
      try {
         final boolean isOreo = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
         String stringContentURI;
         Uri contentUri;
         if(isOreo){
            stringContentURI = "content://downloads/my_downloads";
         }else{
            stringContentURI = "content://downloads/public_downloads";
         }
         contentUri = ContentUris.withAppendedId(
                    Uri.parse(stringContentURI), Long.valueOf(id));
         return getDataColumn(context, contentUri, null, null);
      } catch (NumberFormatException e) {
         return null;
      }
   }
}

public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {   column};
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

但是,当从Android中的其他文件夹中选择文件时,此方法有效设备

请告知。谢谢大家:)

However, it is working when selecting file from other folders in Android device

Please advise. Thanks everyone :)

推荐答案

目前,获取路径的最佳方法是:

从URI作为InputStream获取物理文件,
ContentResolver.openInputStream()允许您访问文件的内容而无需知道其真实路径

For now, the best approach for getting path is :

Getting physical file from URI as InputStream,ContentResolver.openInputStream() allow you to access the contents of a file without knowing its real path

String id = DocumentsContract.getDocumentId(uri);
InputStream inputStream = getContentResolver().openInputStream(uri);

然后将其作为临时文件写入缓存的存储区

then write it as a temporary file in cached storage

File file = new File(getCacheDir().getAbsolutePath()+"/"+id);
writeFile(inputStream, file);
String filePath = file.getAbsolutePath();





void writeFile(InputStream in, File file) {
     OutputStream out = null;
     try {
          out = new FileOutputStream(file);
          byte[] buf = new byte[1024];
          int len;
          while((len=in.read(buf))>0){
            out.write(buf,0,len);
          }
     } catch (Exception e) {
          e.printStackTrace();
     }
     finally {
          try {
            if ( out != null ) {
                 out.close();
            }
            in.close();
          } catch ( IOException e ) {
               e.printStackTrace();
          }
     }
}

不确定是否最好方法,但代码正常运行:D

Not sure if its the best way to do, but the code is working properly :D

这篇关于如何从Android Oreo(8.1)或更高版本中的URI获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 10:01