据我所知,只有三种方法可以通过阅读现有问题来获取 MIME 类型。
1) 使用 MimeTypeMap.getFileExtensionFromUrl
从文件扩展名确定它
2) 使用 inputStream
进行“猜测”与 URLConnection.guessContentTypeFromStream
3) 使用 ContentResolver
使用内容 Uri (content:\) 获取 MIME 类型 context.getContentResolver().getType
但是,我只有文件对象,可获得 Uri
作为文件路径 Uri
(文件:)。该文件没有扩展名。还有办法获取文件的 MIME 类型吗?或者从文件路径Uri判断内容Uri的方法?
最佳答案
你试过吗?它适用于我(仅适用于图像文件)。
public static String getMimeTypeOfUri(Context context, Uri uri) {
BitmapFactory.Options opt = new BitmapFactory.Options();
/* The doc says that if inJustDecodeBounds set to true, the decoder
* will return null (no bitmap), but the out... fields will still be
* set, allowing the caller to query the bitmap without having to
* allocate the memory for its pixels. */
opt.inJustDecodeBounds = true;
InputStream istream = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(istream, null, opt);
istream.close();
return opt.outMimeType;
}
当然你也可以使用其他方法,比如BitmapFactory.decodeFile
或者BitmapFactory.decodeResource
像这样:
public static String getMimeTypeOfFile(String pathName) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, opt);
return opt.outMimeType;
}
如果判断MIME类型失败,则返回null。
关于java - Android - 从没有扩展名的文件中获取 MIME 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18665608/