Getting A File's Mime Type In Java

后端 未结 23 2729
南方客
南方客 2020-11-21 06:53

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

23条回答
  •  野性不改
    2020-11-21 07:28

    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.

提交回复
热议问题