【问题标题】:Best approach to get filename from picked file/image从挑选的文件/图像中获取文件名的最佳方法
【发布时间】:2014-01-24 12:21:36
【问题描述】:

我在这里和那里看到的大多数关于提示用户选择文件或图像的代码 sn-ps,让 onActivityResult 方法使用类似下面的函数来获取所选文件小路。

我的问题是,当 Uri 已经准备好使用函数 Uri.getPath() 时,为什么要经历所有这些?一种方法或另一种方法有优缺点吗?

onActivityResult 代码

   Uri source = data.getData();
   String fileName=getRealPathFromURI(this, source);

获取路径函数

   public static 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();
            }
          }
    }

实际上,当我从保管箱中选择文件/图像时,我的应用程序使用 getRealPathMethod 崩溃了……而使用 Uri.getPath() 方法时,我没有任何问题。所以..这是怎么回事?我错过了什么吗?

【问题讨论】:

  • 您不必拥有文件名即可获取内容。你不应该有一个。 developer.android.com/guide/topics/providers/… 查看打开的输入流/位图示例(该部分不是 android 4.4 独有的)
  • 好的...但这与问题无关。也许我想要做的需要获取文件名而不是内容。
  • 可能连一个文件都没有。或者你无法访问的一个。您不能在所有情况下都使用路径。 (这基本上就是“这里有什么交易?我错过了什么?”的答案)

标签: android image uri filepath


【解决方案1】:

这样试试

final String [] consDirNames  = new String[constDir.length];
        // directory names 
        for(int i=0;i<constDir.length;i++){

            consDirNames[i]=constDir[i].getName();
                    File booths[]=        constDir[i].listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File pathname) {
                            // TODO Auto-generated method stub
                            return pathname.getName().endsWith(".pdf");
                        }
                });    ;
        consDirMap.put(consDirNames[i], booths);
        fileMap.put(consDirNames[i],constDir[i].getAbsolutePath() );
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 2021-01-14
    • 2021-11-11
    • 2016-05-12
    • 1970-01-01
    • 2012-12-12
    • 2021-08-12
    • 1970-01-01
    相关资源
    最近更新 更多