How to fetch the MIME type from byte array in Java

2020-04-05 09:05发布

问题:

I have been trying to figure out how to fetch the MIME type from byte array in Java 6, but unfortunately have not been able fetch the MIME type yet.

Can someone help me get out of this?

回答1:

You can use the MimetypesFileTypeMap provided class from Java 6. This class is exclusively used to fetch the MIME type.

Use it to fetch the MIME type as shown below:

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


回答2:

Good working library https://github.com/overview/mime-types

Import (via 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