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 dirPath = "/home/MyPC/Downloaded";
String fileName = "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(dirPath.concat("/" + fileName));
//Saving the file using Guava
Files.write(fileAsArray, fileToWriteTo);
}
How can I write a file with extension using MimeType?
There are two ways generally:
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).