无法从URI获取文件路径,找不到此类文件或目录异常

时间:2019-05-21 19:21:36

标签: java android ftp filepath filenotfoundexception

我尝试从Android设备获取文件的文件路径,并使用Intent将其存储在FTP服务器上,从URI模板获取的路径初始化了FILE对象,但是当我将此文件对象发送到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;
}

2 个答案:

答案 0 :(得分:0)

您可能将无法从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);
    }
}

答案 1 :(得分:0)

我已经尝试过从设备获取绝对路径,当我从SD卡中选择文件但在内部存储上不起作用时,它工作正常     字符串fullpath = Environment.getExternalStorageDirectory()。getAbsolutePath()+ filePath;