Hemant recently told me about this cool API in java.net.URLConnection 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 :-
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.