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)

Jason S
  • 184,598
  • 164
  • 608
  • 970

3 Answers3

6

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
  • 44,698
  • 7
  • 80
  • 103
6

Yes, URLConnection.guessContentTypeFromName does exactly this.

Jason Day
  • 8,809
  • 1
  • 41
  • 46
0

A hashtable you've loaded with the common types?

Dean J
  • 39,360
  • 16
  • 67
  • 93