2

I have a full file path and would like to determine the MediaType (Google's Guava 19.0) it corresponds to. I thought there would be a built in function in MediaType to accomplish this but I don't think so after experimenting and reading the MediaType API.

I know I can accomplish this by writing a giant switch to return a MediaType based on the file extension but I'd rather not do that if I don't have to.

Is there an easy way to accomplish this or is writing a switch my only option? Thanks - Much Appreciated!

  • 2
    You're aware that the file extension is no guarantee that a file has the associated MIME type, right? I think your best approach would be to use another library designed to sniff MIME types from file contents. – Thorn G Feb 26 '15 at 22:08
  • You're right - I shouldn't have assume any sort of certainty. – Patrick Hovsepian Feb 27 '15 at 14:52

1 Answers1

8

One way to handle this is to use 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, if any, for its behavior.

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • Thank you for the response! The architect has informed me that were going to use an octet stream for this particular application. Also, your method worked with the small sample set I tested with. – Patrick Hovsepian Feb 27 '15 at 15:03