apache tika判断文件类型

判断文件类型一般可采用两种方式

  1. 后缀名判断 
    简单易操作,但无法准确判断类型
  2. 文件头信息判断 
    通常可以判断文件类型,但有些文件类型无法判断(如word和excel头信息的前几个字节是一样的,无法判断)

使用apache.tika可轻松解决以上两种方式存在的问题

 

使用apache.tika判断文件类型

1. maven依赖

<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core -->
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>1.9</version>
</dependency>

2. 具体实现

    private static String getMimeType(File file) {
        if (file.isDirectory()) {
            return "the target is a directory";
        }

        AutoDetectParser parser = new AutoDetectParser();
        parser.setParsers(new HashMap<MediaType, Parser>());

        Metadata metadata = new Metadata();
        metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName());

        InputStream stream;
        try {
            stream = new FileInputStream(file);
            parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());
            stream.close();
        } catch (TikaException | SAXException | IOException e) {
            e.printStackTrace();
        }

        return metadata.get(HttpHeaders.CONTENT_TYPE);
    }

3. 常见文件类型

MimeType 文件类型
application/msword word(.doc)
application/vnd.ms-powerpoint powerpoint(.ppt)
application/vnd.ms-excel excel(.xls)
application/vnd.openxmlformats-officedocument.wordprocessingml.document word(.docx)
application/vnd.openxmlformats-officedocument.presentationml.presentation powerpoint(.pptx)
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet excel(.xlsx)
application/x-rar-compressed rar
application/zip zip
application/pdf pdf
video/* 视频文件
image/* 图片文件
text/plain 纯文本
text/css css文件
text/html html文件
text/x-java-source java源代码
text/x-csrc c源代码
text/x-c++src c++源代码
正因为当初对未来做了太多的憧憬,所以对现在的自己尤其失望。生命中曾经有过的所有灿烂,终究都需要用寂寞来偿还。
原文地址:https://www.cnblogs.com/candlia/p/11919957.html