从MimeType获取扩展名 [英] Get the extension from a MimeType

查看:203
本文介绍了从MimeType获取扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 MimeType 中获取扩展名.

例如:

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

要在Windows或Linux上保存文件,我可以使用这种方法从URL下载文件.因此,我只能保存它而没有扩展名(我不想要那样).

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).

此方法只允许我获取 MimeType ,而不是扩展名.

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);
}

如何使用MimeType编写带有扩展名的文件?

How can I write a file with extension using MimeType?

推荐答案

通常有两种方法:

  • 具有MimeTypes到扩展名的映射;
  • 使用一些逻辑对其进行计算;

第二种方法确实不好,所以我仅提供它作为补充.对于第一种方法,您可以使用以下资源: https://www.freeformatter.com/mime -types-list.html

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

我会使用HashMap<K,V>-键是MimeType,值是扩展名(或类似名称).

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

这篇关于从MimeType获取扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆