您的位置:首页 > 运维架构 > Apache

使用apache.tika判断文件类型

2016-11-11 10:35 531 查看

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

后缀名判断
简单易操作,但无法准确判断类型

文件头信息判断
通常可以判断文件类型,但有些文件类型无法判断(如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++源代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: