如何使用Java从文件中获得媒体类型(MIME类型)?到目前为止,我已经尝试了JMimeMagic和Mime-Util。第一个给了我内存异常,第二个没有正确地关闭它的流。

您将如何探测该文件以确定其实际类型(而不仅仅是基于扩展名)?


当前回答

实际上,Apache Tika检测器Tika.detect(File)是最好的选择,比Files.probeContentType(path)更准确。

检查这个伟大的快速参考包含示例和代码示例。

其他回答

在Java 7中,你现在可以只使用Files.probeContentType(path)。

如果你在linux操作系统上工作,有一个命令行文件——mimetype:

String mimetype(file){

   //1. run cmd
   Object cmd=Runtime.getRuntime().exec("file --mime-type "+file);

   //2 get output of cmd , then 
    //3. parse mimetype
    if(output){return output.split(":")[1].trim(); }
    return "";
}

Then

mimetype("/home/nyapp.war") //  'application/zip'

mimetype("/var/www/ggg/au.mp3") //  'audio/mp3'

检查流或文件的神奇字节:

https://stackoverflow.com/a/65667558/3225638

它使用纯Java,但是要求您定义要检测的类型的枚举。

不幸的是,

mimeType = file.toURL().openConnection().getContentType();

不工作,因为URL的这种使用会使文件被锁定,因此,例如,它是不可删除的。

然而,你有这个:

mimeType= URLConnection.guessContentTypeFromName(file.getName());

还有下面的内容,它的优点不仅仅是使用文件扩展名,还可以查看内容

InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
 //...close stream

然而,正如上面的评论所建议的那样,mime-types的内置表是非常有限的,例如,不包括MSWord和PDF。因此,如果您想要泛化,您将需要使用内置库,例如Mime-Util(这是一个很棒的库,同时使用文件扩展名和内容)。

public String getFileContentType(String fileName) {
    String fileType = "Undetermined";
    final File file = new File(fileName);
    try
    {
        fileType = Files.probeContentType(file.toPath());
    }
    catch (IOException ioException)
    {
        System.out.println(
                "ERROR: Unable to determine file type for " + fileName
                        + " due to exception " + ioException);
    }
    return fileType;
}