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

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


当前回答

在Java中,URLConnection类有一个名为guessContentTypeFromName(String fileName)的方法,可以用来根据文件的文件名猜测文件的MIME媒体类型(也称为内容类型)。该方法使用文件名的扩展名来确定内容类型。

String fileName = "image.jpg";
String contentType = URLConnection.guessContentTypeFromName(fileName);
System.out.println(contentType); // "image/jpeg"

想要了解更多,请阅读这篇文章

其他回答

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

阿帕奇蒂卡。

<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-parsers -->
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>1.24</version>
</dependency>

和两行代码。

Tika tika=new Tika();
tika.detect(inputStream);

截图

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

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

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

如果你是一个Android开发人员,你可以使用一个工具类Android .webkit. mimetypemap,它将mime类型映射到文件扩展名,反之亦然。下面的代码片段可能对您有所帮助。 getMimeType(String fileUrl) { 字符串扩展= MimeTypeMap.getFileExtensionFromUrl(fileUrl); 返回MimeTypeMap.getSingleton () .getMimeTypeFromExtension(扩展); }

我只是想知道大多数人如何从Java文件中获取mime类型?

我已经发布了我的SimpleMagic Java包,它允许从文件和字节数组中确定内容类型(mime类型)。它被设计用来读取和运行Unix文件(1)命令魔法文件,这些文件是大多数~Unix操作系统配置的一部分。

我尝试了Apache Tika,但它很大,有大量的依赖关系,URLConnection不使用文件的字节,MimetypesFileTypeMap也只查看文件名。

使用SimpleMagic,你可以做以下事情:

// create a magic utility using the internal magic file
ContentInfoUtil util = new ContentInfoUtil();
// if you want to use a different config file(s), you can load them by hand:
// ContentInfoUtil util = new ContentInfoUtil("/etc/magic");
...
ContentInfo info = util.findMatch("/tmp/upload.tmp");
// or
ContentInfo info = util.findMatch(inputStream);
// or
ContentInfo info = util.findMatch(contentByteArray);

// null if no match
if (info != null) {
   String mimeType = info.getMimeType();
}