Getting MIME type from a file
Posted by Michele Sun, 10 Sep 2006 03:56:00 GMT
It’s pretty simple: just grab activation framework from the web and type:
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
...
File file = new File("WhoAmI.jpg");
System.out.println("MIME type of " +
file.getName() + " is " +
new MimetypesFileTypeMap().getContentType(file)
);The expected output is:
MIME type of WhoAmI.jpg is image/jpeg
simple and effective, isn’t it?
UPDATE: If you want to detect types other than simple images you should integrate the activation framework default list as stated in the javadoc . For example detection of a zip archive can be done by adding this:
MimetypesFileTypeMap mt = new MimetypesFileTypeMap();
mt.addMimeTypes("application/x-zip zip ZIP");






