Getting A File's Mime Type In Java

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

    With Apache Tika you need only three lines of code:

    File file = new File("/path/to/file");
    Tika tika = new Tika();
    System.out.println(tika.detect(file));
    

    If you have a groovy console, just paste and run this code to play with it:

    @Grab('org.apache.tika:tika-core:1.14')
    import org.apache.tika.Tika;
    
    def tika = new Tika()
    def file = new File("/path/to/file")
    println tika.detect(file)
    

    Keep in mind that its APIs are rich, it can parse "anything". As of tika-core 1.14, you have:

    String  detect(byte[] prefix)
    String  detect(byte[] prefix, String name)
    String  detect(File file)
    String  detect(InputStream stream)
    String  detect(InputStream stream, Metadata metadata)
    String  detect(InputStream stream, String name)
    String  detect(Path path)
    String  detect(String name)
    String  detect(URL url)
    

    See the apidocs for more information.

提交回复
热议问题