How to reliably detect file types?

后端 未结 3 1416
心在旅途
心在旅途 2020-12-01 17:25

Objective: given the file, determine whether it is of a given type (XML, JSON, Properties etc)

Consider the case of XML - Up until we ran into this issue, the follow

3条回答
  •  一向
    一向 (楼主)
    2020-12-01 17:45

    Apache Tika gives me the least amount of issues and is not platform specific unlike Java 7 : Files.probeContentType

    import java.io.File;
    import java.io.IOException;
    import javax.activation.MimeType;
    import org.apache.tika.Tika;
    
    File inputFile = ...
    String type = new Tika().detect(inputFile);
    System.out.println(type);
    

    For a xml file I got 'application/xml'

    for a properties file I got 'text/plain'

    You can however add a Detector to the new Tika()

    
        org.apache.tika
        tika-core
        1.xx
    
    

提交回复
热议问题