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].jpg
Url of the file:
String url = "/mnt/sdcard/mydev/Greatest Hits - Lenny Kravitz (Booklet 01) [2000].jpg";
Function call:
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
But I’m getting an exception on the function call. Is this a bug or a feature?
It works fine for file names that don’t contain that many foreign characters (such as paranthesis).
Is the function buggy? Am I missing something? How am I supposed to differentiate a bug from a feature? I’ve read the function description and it should work properly.
Do you personally use it in your projects? It doesn’t seem reliable.
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:As to why
MimeTypeMap.getFileExtensionFromUrl(url)fails? It’s expecting a properly formated URL String, which yours is not. You should first encode it usingURLEncoder. For example:This should allow
MimeTypeMap.getFileExtensionFromUrl(url)to work properly but unfortunately it still doesn’t. Why?URLEncoderwill change all spaces to a ‘+’ sign andgetFileExtensionFromUrlconsiders 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.