Get the extension from a MimeType

Tajrib :

I want to get the extension from a MimeType.

For example:

video/mp4                       ---->  mp4
application/x-rar-compressed    ---->  rar
text/plain                      ---->  txt
application/pdf                 ---->  pdf

To save my file on Windows or Linux, I have this method that let me to download a file from an URL. So, I'm able only to save it without extension (I don't want that).

This method lets me only to get the MimeType not the extension.

public void DownloadImage() {
    String TheFolderPath = "/home/MyPC/Downloaded";
    String File_NAME = "My downloaded file";

    URL fetchFile = new URL(IMAGE_URL);
    byte[] FileAsArray = Resources.toByteArray(fetchFile);

    //Getting the MimeType
    String MimeType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(FileAsArray));
    System.out.println(MimeType);

    File fileToWriteTo = new File(TheFolderPath.concat("/" + File_NAME));

    //Saving the file using Guava
    Files.write(FileAsArray, fileToWriteTo);
}

How can I write a file with extension using MimeType?

Mindaugas Bernatavičius :

There are two ways generally:

  • have a mapping of MimeTypes to extensions;
  • compute it, using some logic;

The second approach is really not good, so I offer it only for completion. For the first approach you can use this resource: https://www.freeformatter.com/mime-types-list.html

I would use HashMap<K,V> - the key being the MimeType and the value be the extension (or similar).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475412&siteId=1