Getting A File's Mime Type In Java

后端 未结 23 2718
南方客
南方客 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:37

    I was just wondering how most people fetch a mime type from a file in Java?

    I've published my SimpleMagic Java package which allows content-type (mime-type) determination from files and byte arrays. It is designed to read and run the Unix file(1) command magic files that are a part of most ~Unix OS configurations.

    I tried Apache Tika but it is huge with tons of dependencies, URLConnection doesn't use the bytes of the files, and MimetypesFileTypeMap also just looks at files names.

    With SimpleMagic you can do something like:

    // create a magic utility using the internal magic file
    ContentInfoUtil util = new ContentInfoUtil();
    // if you want to use a different config file(s), you can load them by hand:
    // ContentInfoUtil util = new ContentInfoUtil("/etc/magic");
    ...
    ContentInfo info = util.findMatch("/tmp/upload.tmp");
    // or
    ContentInfo info = util.findMatch(inputStream);
    // or
    ContentInfo info = util.findMatch(contentByteArray);
    
    // null if no match
    if (info != null) {
       String mimeType = info.getMimeType();
    }
    

提交回复
热议问题