Apache Tika 是一個內容分析工具包,可以檢測 上千種文件類型 ,並提取它們的 元數據和文本 。tika在設計上十分精巧,單一的接口使它易於使用,在 搜索引擎索引,內容分析,翻譯 等諸多方面得到了廣泛使用。
一般而言我們會使用文件頭的信息來進行判斷
文件頭信息判斷 (魔數)
通常可以判斷文件類型,但有些文件類型無法判斷(如word和excel頭信息的前幾個字節是一樣的,無法判斷)
所以,我們需要尋找一種開源框架來幫助我們來完成文件的格式校驗:
引入依賴:
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.9</version>
</dependency>
工具方法
private static String getMimeType(File file) {
if (file.isDirectory()) {
return "the target is a directory";
}
AutoDetectParser parser = new AutoDetectParser();
parser.setParsers(new HashMap<>());
//元數據
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 (Exception e) {
log.error("", e);
}
return metadata.get(HttpHeaders.CONTENT_TYPE);
}
}
文件類型:
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/ofd |
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++源代碼 |