gpt4 book ai didi

java - 从 MimeType 获取扩展名

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:53:02 25 4
gpt4 key购买 nike

我想从 MimeType 获取扩展名

例如:

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

要在 Windows 或 Linux 上保存我的文件,我有这个方法可以让我从 URL 下载文件。所以,我只能在没有扩展名的情况下保存它(我不想要那样)。

这个方法让我只能得到 MimeType 而不是 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 编写带有扩展名的文件?

最佳答案

一般有两种方式:

  • 将 MimeType 映射到扩展;
  • 计算它,使用一些逻辑;

第二种方法确实不好,所以我只提供它来完成。对于第一种方法,您可以使用此资源:https://www.freeformatter.com/mime-types-list.html

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

关于java - 从 MimeType 获取扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com