How to get a file’s MIME Type in Java

Recently I wanted to attach binary data into emails that the system sent.
Unfortunately, the MIME type was not available to me, so  I used the  JDK interface “java.net.FileNameMap” to extract the mime type.


FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mimeType = Optional.ofNullable(fileNameMap.getContentTypeFor(filename)).orElse("application/octet-stream");

The fileNameMap loads the MIME table. The program above is going to search in the file indicated by the system property named “content.types.user.table”. If the property is not provided the code will load the $JAVA_HOME/jre/lib/content-type.properties

The command bellow is a sample on how the content-type.properties file looks like.


head -n 50 $JAVA_HOME/jre/lib/content-types.properties


content/unknown: description=Unknown Content
unknown/unknown: description=Unknown Data Type


application/octet-stream: \
 description=Generic Binary Stream;\
 file_extensions=.saveme,.dump,.hqx,.arc,.o,.a,.bin,.exe,.z,.gz


application/oda: \
 description=ODA Document;\
 file_extensions=.oda


application/pdf: \
 description=Adobe PDF Format;\
 file_extensions=.pdf


application/postscript: \
 description=Postscript File;\
 file_extensions=.eps,.ai,.ps;\
 icon=ps;\
 action=application;\
 application=imagetool %s


application/x-dvi: \
 description=TeX DVI File;\
 file_extensions=.dvi;\
 action=application;\

A nice article which presents various techniques for extracting the MIME type can be found here : https://www.baeldung.com/java-file-mime-type