Android:我应该使用MimeTypeMap.getFileExtensionFromUrl()吗?[臭虫] [英] Android: should I use MimeTypeMap.getFileExtensionFromUrl()? [bugs]

查看:58
本文介绍了Android:我应该使用MimeTypeMap.getFileExtensionFromUrl()吗?[臭虫]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想使用以下功能从文件URL获取文件扩展名:

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

文件名:

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

文件的网址:

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

函数调用:

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.

推荐答案

当我测试您的代码时,不会为我引发任何异常.虽然没有返回正确的文件扩展名"jpg".我不建议使用 MimeTypeMap .获取文件扩展名的一种简单方法如下:

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);
}

为什么 MimeTypeMap.getFileExtensionFromUrl(url)失败?期望使用格式正确的URL字符串,而您的不是.您应该首先使用 URLEncoder 对其进行编码.例如:

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");

应该允许 MimeTypeMap.getFileExtensionFromUrl(url)正常工作,但不幸的是,它仍然无法正常工作.为什么? URLEncoder 将所有空格更改为'+'号,并且 getFileExtensionFromUrl 认为该字符无效.恕我直言,这是一个错误.

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.

这篇关于Android:我应该使用MimeTypeMap.getFileExtensionFromUrl()吗?[臭虫]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆