【问题标题】:Can Not get Filepath from URI, No such File or Directory Found exception无法从 URI 获取文件路径,未找到此类文件或目录异常
【发布时间】:2019-05-21 19:21:36
【问题描述】:

我尝试从 Android 设备获取文件的文件路径并使用 Intent 将其存储在 FTP 服务器上,文件对象是从我从 URI 模板获得的路径初始化的,但是当我将此文件对象发送到 FileInputStream 它给了我找不到文件的例外

 Uri uri;
    FileInputStream fis = null;
    if (requestCode==6 && resultCode==RESULT_OK && data!=null)
    {
        uri=data.getData();//return URI of selected File
        File fil= null;
        try {
            fil = new File(getRealPathFromURI(uri));
            fis= new FileInputStream(fil);
            client.storeFile(filePath,fis);
        } catch (Exception e) {
            e.getMessage();
        }
 private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = NavigationDrawer.this.getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = 0;//cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

【问题讨论】:

  • urigetRealPathFromURI 的输出是什么样的?您可能根本无法获得绝对文件路径(您可能会发现这个blog post by commonsware useful
  • 这是 Uri "content://com.android.providers.media.documents/document/image%3A13425" 的值,这是 getRealPathFromURI "image:13425" 的输出

标签: java android ftp filepath filenotfoundexception


【解决方案1】:

您可能无法从您的 Uri 访问绝对文件路径。相反,如果您需要文件路径,您可以尝试在该 Uri 上打开 InputStream,并使用它将文件复制到您的应用程序可以访问的位置。例如:

try (InputStream is = context.getContentResolver().openInputStream(uri)) {
    final File file = new File(context.getCacheDir(), "filename");
    try (OutputStream os = new FileOutputStream(file)) {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = input.read(buffer))>0) {
            os.write(buffer, 0, read);
        }
        os.flush();
    }
    //File copy's finished, so you can access its path
    try(FileInputStream fis = new FileInputStream(file)) {
        client.storeFile(file.getAbsolutePath(),fis);
    }
}

【讨论】:

    【解决方案2】:

    我试过这个从设备中获取绝对路径,当我从 SD 卡中选择文件时它工作正常,但在内部存储上没有工作 String fullpath=Environment.getExternalStorageDirectory().getAbsolutePath()+filePath;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      相关资源
      最近更新 更多