Android - 从没有扩展名的文件中获取MIME类型

Jas*_* Hu 11 java android file mime-types

据我所知,只有三种方法可以通过阅读现有问题来获取MIME类型.

1)使用.从文件扩展名确定它 MimeTypeMap.getFileExtensionFromUrl

2)使用inputStreamwith "猜猜"URLConnection.guessContentTypeFromStream

3)使用ContentResolver内容Uri获取MIME类型(内容:\)context.getContentResolver().getType

但是,我只有文件对象,可获取的Uri是文件路径Uri(文件:).该文件没有扩展名.还有办法获取文件的MIME类型吗?或者从文件路径Uri确定内容Uri的方法?

fik*_*r4n 13

你试过这个吗?它适用于我(仅适用于图像文件).

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;
}
Run Code Online (Sandbox Code Playgroud)

当然,你也可以用其他的方法,如BitmapFactory.decodeFileBitmapFactory.decodeResource这样的:

public static String getMimeTypeOfFile(String pathName) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(pathName, opt);
    return opt.outMimeType;
}
Run Code Online (Sandbox Code Playgroud)

如果无法确定MIME类型,它将返回null.


Com*_*are 9

还有办法获取文件的 MIME 类型吗?

不仅仅是文件名。

或者从文件路径Uri确定内容Uri的方法?

不一定有任何“内容 Uri”。欢迎您尝试在其中查找该文件MediaStore,看看它是否由于某种原因碰巧知道 MIME 类型。MediaStore可能知道也可能不知道 MIME 类型,如果不知道,则无法确定它。

如果你content:// Uri,使用getType()ContentResolver获得的MIME类型。