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

标签 java android file mime-types

据我所知,只有三种方法可以通过阅读现有问题来获取 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/

相关文章:

java - Spring 中的 Apache Camel RouteBuilder 不会启动 configure()

python - 如何消除文件: python中的重复行

java - 使用 ActionListener 使用 Formatter 写入文件(JAVA)时出错

linux cp mtime更改

java - 如何使用 Kotlin 扩展 Java 类以像 static fun 一样使用?

android - cordova 相机插件获取所选图像的真实路径

java - 以编程方式将 "Binding Name"添加到 Java Spring 应用程序中的 PCF 服务

java - 重绘()不起作用

java - 使用 SurfaceView 时锁定 Canvas 失败且 Canvas 为空

android - 在 xml 中将 GridView columnWidth 设置为 wrap_content