Reputation: 148
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?
Upvotes: 11
Views: 36065
Reputation: 1578
Apache Tika library is proving to be the most accurate in detecting proper MIME type from a byte array in my tests, much better than Java's URLConnection.guessContentTypeFromStream()
which has proven not very reliable for me.
Upvotes: 1
Reputation: 658
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);
Upvotes: 25
Reputation: 1717
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
Upvotes: 0