在java中确定文件的mime类型的最佳方法? [英] Best way to determine mime type of a file in java?

查看:253
本文介绍了在java中确定文件的mime类型的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很奇怪Java中获取mime类型文件的最佳方式。它应该实际检查文件,因为文件名不是一个准确的指标。

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.

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

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


推荐答案

URLConnection# guessContentTypeFromStream() ... FromName() 确实是标准Java SE API中最好的。然而,像 jMimeMagic 这样的第三方图书馆比 URLConnection#更好地工作guessXXX() methods。

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 jMimeMagic which does its work better than URLConnection#guessXXX() methods.

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

这支持更广泛的mime类型。

This supports a more wide range of mime types.

这篇关于在java中确定文件的mime类型的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆