使用apache.tika判斷文件類型

判斷文件類型通常可採用兩種方式

  1. 後綴名判斷 
    簡單易操做,但沒法準確判斷類型
  2. 文件頭信息判斷 
    一般能夠判斷文件類型,但有些文件類型沒法判斷(如word和excel頭信息的前幾個字節是同樣的,沒法判斷)

使用apache.tika可輕鬆解決以上兩種方式存在的問題css

 

使用apache.tika判斷文件類型html

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++源代碼
相關文章
相關標籤/搜索