使用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/mswordword(.doc)
application/vnd.ms-powerpointpowerpoint(.ppt)
application/vnd.ms-excelexcel(.xls)
application/vnd.openxmlformats-officedocument.wordprocessingml.documentword(.docx)
application/vnd.openxmlformats-officedocument.presentationml.presentationpowerpoint(.pptx)
application/vnd.openxmlformats-officedocument.spreadsheetml.sheetexcel(.xlsx)
application/x-rar-compressedrar
application/zipzip
application/pdfpdf
video/*视频文件
image/*图片文件
text/plain纯文本
text/csscss文件
text/htmlhtml文件
text/x-java-sourcejava源代码
text/x-csrcc源代码
text/x-c++srcc++源代码

 

转载于:https://my.oschina.net/lvzhitao/blog/786045

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值