在java中确定文件的mime类型的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3576129/
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-14 02:02:10  来源:igfitidea点击:

Best way to determine mime type of a file in java?

javaimagemime-types

提问by James

Curious what the best way is in Java to get the mime-type of a file. It should actually inspect the file because filenames aren't an accurate indicator.

好奇在 Java 中获取文件的 MIME 类型的最佳方法是什么。它实际上应该检查文件,因为文件名不是一个准确的指标。

Currently I'm using the following which seems to be very hit or miss

目前我正在使用以下似乎很受欢迎或错过的

  is = new BufferedInputStream(new FileInputStream(fileName));
  String mimeType = URLConnection.guessContentTypeFromStream(is);
  if(mimeType == null) {
    throw new IOException("can't get mime type of image");
  }

采纳答案by BalusC

The URLConnection#guessContentTypeFromStream()or ...FromName()is indeed the best what you can get in the standard Java SE API. There are however 3rd party libraries like jMimeMagicwhich does its work better than URLConnection#guessXXX()methods.

URLConnection#guessContentTypeFromStream()...FromName()确实是你可以在标准的Java SE API中得到最好的。然而,有像jMimeMagic这样的3rd 方库比URLConnection#guessXXX()方法做得更好。

String mimeType = Magic.getMagicMatch(file, false).getMimeType();

This supports a more wide range of mime types.

这支持更广泛的 mime 类型。

回答by vikasing

Following link has a good comparison of various ways of getting the Mime type of a file (it includes libraries like: Apache Tika, JMimeMagic etc. with some native code too): http://www.rgagnon.com/javadetails/java-0487.html

以下链接对获取文件的 Mime 类型的各种方法进行了很好的比较(它包括诸如 Apache Tika、JMimeMagic 等库以及一些本机代码):http://www.rgagnon.com/javadetails/java- 0487.html

回答by Ray Hulha

    public static String getContentType(String filename)
    {
        String g = URLConnection.guessContentTypeFromName(filename);
        if( g == null)
        {
            g = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filename);
        }
        return g;
    }