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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18665608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:58:22  来源:igfitidea点击:

Android - Get MIME type from file without extension

javaandroidfilemime-types

提问by Jason Hu

As far as I'm aware there's only three ways to get the MIME type from reading the existing questions.

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

1) Determining it from the file extension using MimeTypeMap.getFileExtensionFromUrl

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

2) "Guess" using the inputStreamwith URLConnection.guessContentTypeFromStream

2) 使用inputStreamwith 的“猜测”URLConnection.guessContentTypeFromStream

3) Using the ContentResolverto get the MIME type using content Uri (content:\) context.getContentResolver().getType

3) 使用ContentResolvercontent Uri (content:\) 来获取 MIME 类型context.getContentResolver().getType

However, I only have the file object, with the obtainable Uribeing the file path Uri(file:). The file does not have an extension. Is there still a way to get the MIME type of the file? Or a way to determine the content Uri from the file path Uri?

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

采纳答案by CommonsWare

Is there still a way to get the MIME type of the file?

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

Not from the filename alone.

不仅仅是文件名。

Or a way to determine the content Uri from the file path Uri?

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

There is not necessarily any "content Uri". You are welcome to try to find the file in MediaStoreand see if, for some reason, it happens to know the MIME type. MediaStoremay or may not know the MIME type, and if it does not, there is no way to determine it.

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

If you dohave content://Uri, use getType()on a ContentResolverto get the MIME type.

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

回答by fikr4n

Have you tried this? It works for me (only for image files).

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

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

Of course you can also use other methods, such as BitmapFactory.decodeFileor BitmapFactory.decodeResourcelike this:

当然你也可以使用其他的方法,比如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;
}

It will return null if failed to determine the MIME type.

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

回答by Василий Никитин

First bytes contains file extension

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

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