Android Uri获取真实路径以及文件名的方法

时间:2025-01-30 13:10:43

在Android 编程中经常会用到uri转化为文件路径
下面是4.4后通过Uri获取路径以及文件名一种方法

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

等到的路径 /storage/emulated/0/图片/浪费-林宥嘉.mp3

怎么获取文件名呢?

 String path="/storage/emulated/0/图片/浪费-林宥嘉.mp3";
                String b = path.substring(path.lastIndexOf("/") + 1, path.length());

通过索引最后一个/就可以在String中截取了