Mime-util is a very small, easy-to-use MIME detection library for Java. It can be used for any type of Java application and can detect MIME types from different sources like File, InputStream, URLConnection, byte array etc. Recently 1.3 version of the library was released and had a look at it.
The new release brings in some changes in packages by deprecating eu.medsea.util and bringing in eu.medsea.mimeutil package. The library still has the old package for backward compatibility. The MIME detection is based on the Unix magic mime files which is used by Unix file command. When using the library, it actually tries to access this file for detecting the MIME type. For other platforms, the library uses an internal copy of magic.mime file. This is available in eu.medsea.mimeutil
Working with the library is very simple. I tried out a simple swing application where the user will select a file using JFileChooser and the MIME type is detected and displayed. Assuming that you have got the absolute path of the file, here is my code:
FileInputStream fis = new FileInputStream(dataDisplayLabel.getText());
BufferedInputStream bis = new BufferedInputStream(fis);
MimeUtil mimeUtilObject = new MimeUtil();
log.warn("Support for Mark and Reset: " + fis.markSupported());
log.warn("Support for Mark and Reset: " + bis.markSupported());
log.info("Stream size: " + fis.available());
Collection coll = mimeUtilObject.getMimeTypes(bis);
log.info(coll.size());
Iterator itr = coll.iterator();
while(itr.hasNext()) {
MimeType mt = itr.next();
log.info("Media type: " + mt.getMediaType());
log.info("Sub Type: " + mt.getSubType());
}
One important point to note is that FileInputStream does not support mark and reset methods. For MIME detection, you will have to provide a InputStream that supports mark and reset methods. In this case, I have used BufferedInputStream and it is fed into getMimeTypes method. After detection of MIME type all the methods they return a collection. You will have to iterate this collection and get media type and sub type using separate APIs.Even though this library will not be frequently used, it can be used for validation of files during upload or transfer. It is not always safe to check the file extension and proceed with your program logic. You can download mime-util library from sourceforge.