使用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/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 | |
video/* | 视频文件 |
image/* | 图片文件 |
text/plain | 纯文本 |
text/css | css文件 |
text/html | html文件 |
text/x-java-source | java源代码 |
text/x-csrc | c源代码 |
text/x-c++src | c++源代码 |
相关文章推荐
- 使用lstat()判断文件类型
- 使用lstat()判断文件类型
- 使用lstat()判断文件类型
- 使用ASP.NET 上传文件 三种类型判断方法(后缀,MIME,数据流)
- 使用lstat()判断文件类型
- 使用文件头判断文件类型(出自Rainsilence)
- asp.net上传文件使用fileupload控件,判断文件类型和大小,取得文件路径时报错【System.IO.FileNotFoundException:未能找到文件】的解决办法
- Python使用filetype精确判断文件类型 (文件类型获取)
- 使用apache.tika判断文件类型
- 判断不同类型的文件,使用scp命令在各个主机上传输文件,保持文件的一致性
- 判断数据库启动时使用的参数文件类型的方法
- 使用lstat()判断文件类型
- Android系统使用MediaFile类判断音频文件类型
- 交互式让用户输入一个文件路径,判断文件是否存在,若存在判断文件类型,若文件是普通文件,不能使用wc。
- 在jsp/servlet中使用apache FileUpload组件文件上传(jsp,servlet,fileupload)
- 使用dos批处理文件的几个高级命令,判断
- 使用apache的commons-fileupload实现多文件上传
- oracle 索引表下标使用VARCHAR2类型判断主叫号码
- 在apache配置文件中使用IfDefine以及IfModule指令来快速更改配置
- Js-客户端判断上传文件的类型