I was just wondering how most people fetch a mime type from a file in Java? So far I've tried two utils: JMimeMagic
& Mime-Util
.
The first gave me memory exceptions, the second doesn't close its streams off properly. I was just wondering if anyone else had a method/library that they used and worked correctly?
This is the simplest way I found for doing this:
The JAF API is part of JDK 6. Look at
javax.activation
package.Most interesting classes are
javax.activation.MimeType
- an actual MIME type holder - andjavax.activation.MimetypesFileTypeMap
- class whose instance can resolve MIME type as String for a file:If you are stuck with java 5-6 then this utility class from servoy open source product.
You only need this function
It probes the first bytes of the content and returns the content types based on that content and not by file extension.
In Java 7 you can now just use
Files.probeContentType(path)
.I tried several ways to do it, including the first ones said by @Joshua Fox. But some don't recognize frequent mimetypes like for PDF files, and other could not be trustable with fake files (I tried with a RAR file with extension changed to TIF). The solution I found, as also is said by @Joshua Fox in a superficial way, is to use MimeUtil2, like this:
With Apache Tika you need only three lines of code:
If you have a groovy console, just paste and run this code to play with it:
Keep in mind that its APIs are rich, it can parse "anything". As of tika-core 1.14, you have:
See the apidocs for more information.