I was just wondering how most people fetch a mime type from a file in Java? So far I\'ve tried two utils: JMimeMagic
& Mime-Util
.
Th
Apache Tika offers in tika-core a mime type detection based based on magic markers in the stream prefix. tika-core
does not fetch other dependencies, which makes it as lightweight as the currently unmaintained Mime Type Detection Utility.
Simple code example (Java 7), using the variables theInputStream
and theFileName
try (InputStream is = theInputStream;
BufferedInputStream bis = new BufferedInputStream(is);) {
AutoDetectParser parser = new AutoDetectParser();
Detector detector = parser.getDetector();
Metadata md = new Metadata();
md.add(Metadata.RESOURCE_NAME_KEY, theFileName);
MediaType mediaType = detector.detect(bis, md);
return mediaType.toString();
}
Please note that MediaType.detect(...)
cannot be used directly (TIKA-1120). More hints are provided at https://tika.apache.org/1.24/detection.html.