使用 Guava 19.0,有没有办法将文件扩展名映射到 MediaType?

Using Guava 19.0, is there a way to map a file extension to a MediaType?

我有一个完整的文件路径,想确定它对应的MediaType(Google的Guava 19.0)。我认为 MediaType 中会有一个内置函数来完成此操作,但在试验和阅读 MediaType API.

后我不这么认为

我知道我可以通过编写一个巨大的开关来完成此操作 return 基于文件扩展名的 MediaType,但如果没有必要,我宁愿不这样做。

是否有一种简单的方法可以完成此操作,或者编写一个开关是我唯一的选择? 谢谢 - 非常感谢!

处理此问题的一种方法是对其行为使用 Files.probeContentType(Path) (JDK 7) to try to get the content type. If that returns non-null, you can use MediaType.parse(String) to get it as a MediaType. Keep in mind, though, that probeContentType is entirely dependent on the installed FileTypeDetectors(如果有)。