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

查看:29
本文介绍了从 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 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);
}

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

How can I write a file with extension using MimeType?

推荐答案

一般有两种方式:

  • 有一个 MimeType 到扩展的映射;
  • 使用一些逻辑计算它;

第二种方法确实不好,所以我提供它只是为了完成.对于第一种方法,您可以使用此资源: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 - 键是 MimeType,值是扩展名(或类似的).

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

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

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