views:

64

answers:

2

Curious what the best way is in Java to get the mime-type of a file. It should actually inspect the file because filenames aren't an accurate indicator.

Currently I'm using the following which seems to be very hit or miss

  is = new BufferedInputStream(new FileInputStream(fileName));
  String mimeType = URLConnection.guessContentTypeFromStream(is);
  if(mimeType == null) {
    throw new IOException("can't get mime type of image");
  }
+4  A: 

The URLConnection#guessContentTypeFromStream() or ...FromName() is indeed the best what you can get in the standard Java SE API. There are however 3rd party libraries like jMimeMagic which does its work better than URLConnection#guessXXX() methods.

String mimeType = Magic.getMagicMatch(file, false).getMimeType();

This supports a more wide range of mime types.

BalusC
thanks! will give it a try
You're welcome.
BalusC