【问题标题】:Android - Get MIME type from file without extensionAndroid - 从没有扩展名的文件中获取 MIME 类型
【发布时间】:2013-09-11 00:23:29
【问题描述】:

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

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

2) 使用inputStreamURLConnection.guessContentTypeFromStream“猜测”

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

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

【问题讨论】:

标签: java android file mime-types


【解决方案1】:

你试过了吗?它适用于我(仅适用于图像文件)。

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。

【讨论】:

  • BitmapFactory 只会确定图像文件的 MIME 类型。
【解决方案2】:

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

不仅仅是文件名。

或者从文件路径Uri中判断内容Uri的方法?

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

如果您确实拥有content:// Uri,请在ContentResolver 上使用getType() 以获取MIME 类型。

【讨论】:

    【解决方案3】:

    第一个字节包含文件扩展名

    @Nullable
    public static String getFileExtFromBytes(File f) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f);
            byte[] buf = new byte[5]; //max ext size + 1
            fis.read(buf, 0, buf.length);
            StringBuilder builder = new StringBuilder(buf.length);
            for (int i=1;i<buf.length && buf[i] != '\r' && buf[i] != '\n';i++) {
                builder.append((char)buf[i]);
            }
            return builder.toString().toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-14
      • 2010-11-05
      • 2015-06-13
      • 2015-10-03
      • 2013-11-10
      • 1970-01-01
      相关资源
      最近更新 更多