Determine MIME type in Java

In this article we will see how to determine the MIME type of a file in Java.


A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) is a standard that indicates the nature and format of a document, file, or assortment of bytes. It is defined and standardized in IETF’s RFC 6838.

Browsers use the MIME type, not the file extension, to determine how to process a URL, so it’s important that web servers send the correct MIME type in the response’s Content-Type header. If this is not correctly configured, browsers are likely to misinterpret the contents of files and sites will not work correctly, and downloaded files may be mishandled.


We will make use of MimeUtil. Add the below dependencies in you pom.xml:


We need to register the Mime detector as well:

static {

The below method will get the MIME type from the content which is passed as a byte array:

public static String getMimeType(byte[] content) {
    final Collection mimeTypes = MimeUtil.getMimeTypes(content);
    return MimeUtil.getFirstMimeType(mimeTypes.toString()).toString();

The full source code can be found at java-mime-type


Below is the code snippet for the test:

public void testGetMimeType_jpeg() throws IOException {
    final byte[] bytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("jpeg.jpeg"));
    final String mimeType = MimeTypeDeterminer.getMimeType(bytes);
    assertEquals("image/jpeg", mimeType);

public void testGetMimeType_png() throws IOException {
    final byte[] bytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("png.png"));
    final String mimeType = MimeTypeDeterminer.getMimeType(bytes);
    assertEquals("image/png", mimeType);


In this article we saw how to extract the MIME information for a file in Java. Please note this is not the only way, there are other ways which you can use to do the same thing.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: