views:

77

answers:

3

I have a Java application which sometimes has to generate a Content-Type header from a filename alone. Is there a way to estimate the Content-Type for common extensions? (e.g. ".pdf" maps to "application/pdf", etc)

A: 

A hashtable you've loaded with the common types?

Dean J
+6  A: 

Yes, via the JavaBeans Activation Framework (javax.activation).

import java.io.File;
import javax.activation.MimetypesFileTypeMap;
...
return new MimetypesFileTypeMap().getContentType(new File("brognitz.jpg"));

You can also add your own content types if the Java built-in database is inadequate.

Edit: Jason Day's answer is just as correct, as far as I can tell.

Jonathan Feinberg
+5  A: 

Yes, URLConnection.guessContentTypeFromName does exactly this.

Jason Day