Android: should I use MimeTypeMap.getFileExtensionFromUrl()? [bugs]

前端 未结 3 962
情歌与酒
情歌与酒 2021-02-20 06:48

For example, I wanted to get the file Extension from the file URL using the function below:

File name:

Greatest Hits - Lenny Kravitz (Booklet 01) [2000]         


        
3条回答
  •  我寻月下人不归
    2021-02-20 07:20

    When I test your code, no exception is thrown for me. Though the proper file extension "jpg" is not returned. I would not advise using MimeTypeMap. An easy way to obtain the file extension instead is as follows:

    String file = "/mnt/sdcard/mydev/Greatest Hits - Lenny Kravitz (Booklet 01) [2000].jpg";
    String exten = "";
    
    int i = file.lastIndexOf('.');
    if (i > 0) {
        exten = file.substring(i+1);
    }
    

    As to why MimeTypeMap.getFileExtensionFromUrl(url) fails? It's expecting a properly formated URL String, which yours is not. You should first encode it using URLEncoder. For example:

    String url = "/mnt/sdcard/mydev/Greatest Hits - Lenny Kravitz (Booklet 01) [2000].jpg";
    url = URLEncoder.encode(url, "UTF-8");
    

    This should allow MimeTypeMap.getFileExtensionFromUrl(url) to work properly but unfortunately it still doesn't. Why? URLEncoder will change all spaces to a '+' sign and getFileExtensionFromUrl considers that an invalid character. This part, IMHO, is a bug.

    From my experience, most people don't use this method. In fact, I never heard of it until you posted this question. Probably because finding a file extension is fairly trivial and most people write code similar to what I posted above.

提交回复
热议问题