Friday, June 08, 2007

Finding mime type of any file

Hemant recently told me about this cool API in which can tell you the mime type for common file types.

guessContentTypeFromName(String name) - that simply checks the extension of the file name specified and gets the mime type from a static map it maintains. This can be very useful in many scenarios. The map it uses is quite extensive and contains almost all the mime types.

But this has a problem. What if some one has renamed a gif to jpg? This method will say that the file is a jpg image whereas it was a gif.

Thankfully there is another method in the same class which can address this problem.

guessContentTypeFromStream(InputStream stream) - which reads the stream, takes a look at the initial bits of the file and uses that to determine the file type.
This method does a check for the following mime types :-

- application/java-vm
- application/x-java-serialized-object
- text/html
- application/xml
- image/gif
- image/x-bitmap
- image/x-pixmap
- image/png
- image/jpeg
- image/jpg
- image/vnd.fpx
- audio/basic
- audio/x-wav

Though this method leaves out many of other common types such as mp3, it is still very useful. This makes it so easy to find out the type of an image.

1 comment:

Aaron Neff said...

Thank you Rupesh. Native MP3 support in Java Sound would be nice.