How to determine the file extension of a file from a uri

后端 未结 8 1854
一向
一向 2020-12-13 19:06

Assuming I am given a URI, and I want to find the file extension of the file that is returned, what do I have to do in Java.

For example the file at http://www.daml.

8条回答
  •  佛祖请我去吃肉
    2020-12-13 19:42

    This link might help for those who are still having problems: How I can get the mime type of a file having its Uri?

     public static String getMimeType(Context context, Uri uri) {
        String extension;
    
        //Check uri format to avoid null
        if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //If scheme is a content
            final MimeTypeMap mime = MimeTypeMap.getSingleton();
            extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
        } else {
            //If scheme is a File
            //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
            extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
    
        }
    
        return extension;
    }
    

提交回复
热议问题