如何从 Java 6 中的字节数组中获取 MIME 类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33998407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch the MIME type from byte array in Java 6?
提问by Dinesh Padmanabhan
I have been trying to figure out how to fetch the MIME typefrom byte array in Java 6, but unfortunately have not been able fetch the MIME type yet.
我一直试图弄清楚如何从 Java 6 中的字节数组中获取MIME 类型,但不幸的是还无法获取 MIME 类型。
Can someone help me get out of this?
有人能帮我摆脱这种情况吗?
回答by mayank agrawal
You can use the MimetypesFileTypeMap
provided class from Java 6. This class is exclusively used to fetch the MIME type.
您可以使用MimetypesFileTypeMap
Java 6 中提供的类。该类专门用于获取MIME 类型。
Use it to fetch the MIME type as shown below:
使用它来获取 MIME 类型,如下所示:
byte[] content = ;
InputStream is = new BufferedInputStream(new ByteArrayInputStream(content));
String mimeType = URLConnection.guessContentTypeFromStream(is);
For fetching from File you can use below code:
要从文件中获取,您可以使用以下代码:
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String mime = mimeTypesMap.getContentType(file);
回答by MrSpock
Good working library https://github.com/overview/mime-types
良好的工作库https://github.com/overview/mime-types
Import (via gradle.kts):
导入(通过 gradle.kts):
implementation("org.overviewproject:mime-types:0.1.3")
Usage
用法
// input
final var fileName = "somefile.html";
final var content = "<html></html>".getBytes();
final var mimeTypeDetector = new MimeTypeDetector(); // initialize only once, reuse!
final var mimeType = mimeTypeDetector.detectMimeType(fileName, () -> content);
System.out.println(mimeType); // prints: text/html