Android:将Uri对象转换为File
创始人
2024-10-13 13:01:02
0

要将一个Uri对象转换为File对象,可以使用以下代码:

public File getFileFromUri(Uri uri) {
    String filePath = null;
    if (DocumentsContract.isDocumentUri(context, uri)) {
        String wholeID = DocumentsContract.getDocumentId(uri);

        // Split at colon, use second item in the array
        String[] splits = wholeID.split(":");
        if (splits.length == 2) {
            String id = splits[1];

            String[] projection = {MediaStore.Images.Media.DATA};
            String selection = MediaStore.Images.Media._ID + "=?";
            String[] selectionArgs = {id};

            Cursor cursor = context.getContentResolver()
                    .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(column_index);
            }
            cursor.close();
        }
    } else {
        filePath = uri.getPath();
    }

    if (filePath != null) {
        return new File(filePath);
    } else {
        return null;
    }
}

如果Uri是一个Document Uri,它需要解析出ID才能访问文件。对于其他类型的Uri,可以使用getPath方法获得它的路径。

相关内容

热门资讯

玩家必看教程!werplan有... 自定义wepoker俱乐部辅助系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助...
重大通报!wepoker透视有... 重大通报!wepoker透视有吗,wepoker透视脚本网页,必赢教程(有挂教程)1、玩家可以在we...
我来分享!impoker辅助,... 我来分享!impoker辅助,uupoker透视,实用技巧(有挂透视);原来确实真的有挂(需添加指定...
一分钟了解!sohoo开挂辅助... 一分钟了解!sohoo开挂辅助,wepoker透视功能下载,黑科技教程(有挂技巧);玩家必备必赢加哟...
揭秘攻略!pokemmo脚本,... 您好,pokemmo脚本这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家...
一分钟带你了解!hhpoker... 一分钟带你了解!hhpoker真能买到挂吗,德州来玩辅助器,解说技巧(有挂教程);实战中需综合运用上...
我来教大家!xpoker辅助怎... 我来教大家!xpoker辅助怎么用,werplan辅助软件,细节揭秘(有挂技巧);人气非常高,ai更...
一分钟了解!约局吧是否有挂,如... 1、一分钟了解!约局吧是否有挂,如何下载wpk透视版,科技教程(有挂方法);详细教程。2、如何下载w...
重大发现!pokemmo手机版... 重大发现!pokemmo手机版修改器,wepoker手机版辅助,攻略教程(有挂攻略)是一款可以让一直...
玩家必看攻略!pokemomo... 1、玩家必看攻略!pokemomo辅助软件,hhpoker可以控制牌吗,安装教程(有挂辅助)(UU ...