如何处理内容:// Uri以打开文件

问题描述 投票:1回答:2

我正在使用Android的DownloadManager类。单击“下载文件”通知后,它返回Uricontent://方案。我有一个方法,现在只能使用文件Uris打开文件(使用“文件”方案)。从内容Uri获取File file的最简单方法是什么?欢迎任何例子。

public PlsReader(URI path) {

   File file = new File(path);
}
android url android-contentprovider
2个回答
-2
投票

尝试第一种方法得到的是下面

Uri.getPath();

这将给你任何文件的绝对路径

第二种方法如下

  Strinf absolutepath =   getRealPathFromURI(this,URI);

和方法getRealPathFromURI在这里

  public String getRealPathFromURI(Context context, Uri contentUri) {
      Cursor cursor = null;
      try { 
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }
    }

然后将此绝对路径字符串传递给您的文件

public PlsReader(String absolutepath ) {

   File file = new File(absolutepath );
}

祝你好运dude :)


0
投票

使用Context#getContentResolver().openInputStream(uri)从Uri获取InputStream。

或者使用Context#getContentResolver().openFileDescriptor()获取ParcelFileDescriptor。然后使用ParcelFileDescriptor#getFileDescriptor()获取FileDescriptor。

© www.soinside.com 2019 - 2024. All rights reserved.