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");

Socialize it: Add to del.icio.us Digg it! Technorati: Getting MIME type from a file Add to reddit.com

Posted in ,  | Tags , , ,  | no comments | no trackbacks


SeeSaw srl - Via Monte Pasubio, 8 37126 Verona - tel +39 045 4857457 fax 045 4851151 P.Iva 03609790237