• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4682
  • Last Modified:

Extract file extension from mime type

I have been using:

URLConnection uc = url.openConnection();
String origMimeType = uc.getContentType();

to get the mimetype of a file from url. It will extract the mime type of the file based on JAVA_HOME/lib/content-types.properties file.

But now, I need an opposite method to get the file extension back from the file mime type.

Is there a method available to do this?

I saw this post:

But it's suggesting loading another "mimetype to file extension conversion" reference list. I would like to use the one I've used to be consistent which is the content-type.properties file.

If possible, I would avoid manually parse the file.

Here is part of the content-types.properties file:

application/octet-stream: \
      description=Generic Binary Stream;\

application/oda: \
      description=ODA Document;\

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

Thanks a lot!
  • 2
1 Solution
There are only 60 in my version - is that really enough?
Well - what needs to be returned if more that one extenstion is specified for the type? (just trying to get the technical part cleared - I do not think that there is a ready to use mething)

If the file looks like above, just parse it... should not be that hard I think.
mybluegrassAuthor Commented:
I ended up using MimeTable to do this. Here is what I've done. If there are multiple extension returned, I just used the last one for now.

  public static String getFileExt(String mimeType) {
    String extension = "";

    MimeTable testTable = MimeTable.getDefaultTable();
    Enumeration e = testTable.elements();
    while (e.hasMoreElements()) {
      MimeEntry entry = (MimeEntry) e.nextElement();
      String contentType = entry.getType();
      String extensionString = entry.getExtensionsAsList();
      String[] extensionArray = extensionString.split(",");
      extensionString = extensionArray[extensionArray.length - 1];
      mimeType = mimeType.replaceAll("/", ".*");
      if (contentType.matches(mimeType)) {
        extension = extensionString;
    return extension;
Not such a good idea to use unsupported classes -you will get warnings and what's more the default doesn't contain many extensions anyway
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now