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");
}
解决方案
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.