【问题标题】:Android Getting file name and path from onActivityResultAndroid 从 onActivityResult 获取文件名和路径
【发布时间】:2016-02-02 09:54:14
【问题描述】:

我正在努力实现的目标。我有一个button,当单击该按钮时,应用程序会打开一个文件选择器并且用户选择一个文件。然后应用程序使用FileInputStream 读取文件并生成byte[]。我在button 下方有一个TextView,然后它将简单地显示byte[].length。这是button.onClick()事件中的代码:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");

    requestFilePickerCode = parent.registerActivityResultListener(this);
    try
    {
        parent.startActivityForResult(intent, requestFilePickerCode);
    }
    catch (ActivityNotFoundException e)
    {
        Toast.makeText(task.getParent(), "Please install a file manager", Toast.LENGTH_SHORT).show();
    }

现在这段代码可以工作了,我已经确认它会在选择文件时触发onActivityResult。我只是打印一个Log 来显示data.toString(),它会产生以下输出:

11-02 15:14:36.196 2535-2535/? V/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> content:/com.android.providers.downloads.documents/document/1

所以它似乎正在获取选定的文件。当我运行应用程序并选择一个文件时,它会引发我的自定义错误:

11-02 15:14:36.196 2535-2535/? E/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> File does not exist

这显然表明我没有得到文件。这是我的代码:

@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data)
{
    byte[] fileContent;

    // check that data is not null and assign to file if not null
    if (data != null)
    {
        Uri uri = data.getData();
        String uriString = uri.toString();
        file = new File(uriString);

        Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> " + file.toString());

        // declare file input stream and read bytes
        // write to string variable to test and test output
        FileInputStream fin = null;
        try
        {
            fin = new FileInputStream(file);
            fileContent = new byte[(int) file.length()];

            fin.read(fileContent);
            String test = new String(fileContent);
            Log.v(PebbleTypeHandlerBinary.class.toString(), "=====> " + test);
        }
        catch (FileNotFoundException e)
        {
            Toast.makeText(task.getParent(), "File not found", Toast.LENGTH_SHORT).show();
            Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> File does not exist");
        }
        catch (IOException e)
        {
            Toast.makeText(task.getParent(), "Error reading file", Toast.LENGTH_SHORT).show();
            Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error while reading the file");
        }
        finally
        {
            // close the file input stream to stop mem leaks
            try
            {
                if (fin != null)
                {
                    fin.close();
                }
            } catch (IOException e)
            {
                Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error closing the stream");
            }
        }

        Log.v(PebbleTypeHandlerBinary.class.toString(), data.toString());
    }

    return false;
}

请你们检查我的代码并帮助我完成这项工作。任何帮助将不胜感激。

【问题讨论】:

    标签: android file path


    【解决方案1】:

    /* 你可以用这个方法得到名字和大小。

    • 使用光标。
    • Uri uri = data.getData();
    • 从 onActivityResult() 获取数据 */;

    Cursor cursor = getContentResolver().query(uri, null, null, null, null);

        int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
        cursor.moveToFirst();
    
        String name = cursor.getString(nameIndex);
        String size = Long.toString(cursor.getLong(sizeIndex));
    
        Toast.makeText(this, "name : "+name+"\nsize : "+size, Toast.LENGTH_SHORT).show();
    

    【讨论】:

      【解决方案2】:

      我设法修复它如下:

      我使用inputStream = task.getParent().getContentResolver().openInputStream(uri); 获得InputStream。然后使用ByteArrayOutputStream 写入字节[]。请参阅下面的代码。

      @Override
      public boolean onActivityResult(int requestCode, int resultCode, Intent data)
      {
          Uri uri = data.getData();
          byte[] fileContent;
          InputStream inputStream = null;
      
          try
          {
              inputStream = task.getParent().getContentResolver().openInputStream(uri);
              if (inputStream != null)
              {
                  fileContent = new byte[(int)file.length()];
                  inputStream.read(fileContent);
                  fileContent = new byte[1024];
                  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                  int read;
                  while((read=inputStream.read(fileContent))>-1) baos.write(fileContent,0,read);
                  fileContent = baos.toByteArray();
                  baos.close();
                  Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> Input Stream: " + inputStream);
                  Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> Byte Array: " + fileContent.length);
              }
              else
              {
                  Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Input Stream is null");
              }
          }
          catch (FileNotFoundException e)
          {
              Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> File not found", e);
          }
          catch (IOException e)
          {
              Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error reading file", e);
          }
          finally
          {
              if (inputStream != null)
              {
                  try
                  {
                      inputStream.close();
                  }
                  catch (IOException e)
                  {
                      Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error reading file", e);
                  }
              }
          }
      
          return false;
      }
      

      感谢您的所有帮助。

      【讨论】:

        【解决方案3】:

        您可以搜索将uri 转换为filepath。

        GetData() 重新运行一个 uri。

        但是new File() 需要一个filepath 参数;

        像这样:

        public static String getRealFilePath( final Context context, final Uri uri ) {
            if ( null == uri ) return null;
            final String scheme = uri.getScheme();
            String data = null;
            if ( scheme == null )
                data = uri.getPath();
            else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
                data = uri.getPath();
            } else if
        ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
        
        Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
                if ( null != cursor ) {
                    if ( cursor.moveToFirst() ) {
        
        int index = cursor.getColumnIndex( ImageColumns.DATA );
                        if ( index > -1 ) {
                            data = cursor.getString( index );
                        }
                    }
                    cursor.close();
                }
            }
            return data;
        }
        

        【讨论】:

        • 感谢您为我指明了正确的方向。我现在已将代码更改为 ` Uri uri = data.getData();字符串 uriString = uri.getPath();文件 = 新文件(uriString); // 字符串路径 = file.getAbsolutePath(); Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> " + uriString);`。这仍然会抛出 File not found...
        • 我已设法更改代码以获取路径,谢谢,但它仍然抛出未找到文件。堆栈跟踪现在将路径打印如下:11-02 19:21:57.073 7506-7506/? V/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> /document/2
        • 你不能简单地使用 uri.getPath() 获取文件路径
        猜你喜欢
        • 2015-05-03
        • 1970-01-01
        • 2017-06-17
        • 2011-11-16
        • 2014-12-21
        • 2012-01-21
        • 2015-04-22
        • 2014-07-24
        相关资源
        最近更新 更多