apache tika检测文件是否损坏

Apache Tika用于文件类型检测和从各类格式的文件内容提取的库。apache

将上传文件至服务器,进行解析文件时,常常须要判断文件是否损坏。咱们可使用tika来检测文件是否损坏服务器

  • maven引入以下:
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-app</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency>

  若是jar包冲突时能够引入以下:app

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>1.18</version>
</dependency>
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>1.18</version>
</dependency>
<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>2.11.0</version>
</dependency>
  • 使用tika检测文件是否损坏: 

  若是从输入流读取失败,则parse方法抛出IOException异常,从流中获取的文档不能被解析抛TikaException异常,处理器不能处理事件则抛SAXException异常maven

  当文档不能被解析时,说明文档损坏测试

  • 执行过程:
public static void main(String[] args) {
        try {
            //Assume sample.txt is in your current directory
            File file = new File("D:\\测试.txt");
            boolean result = isParseFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证文件是否损坏
     *
     * @param file 文件
     * @return true/false
     * @throws Exception
     */
    private static boolean isParseFile(File file) throws Exception {
        try {
            Tika tika = new Tika();
            String filecontent = tika.parseToString(file);
            System.out.println(filecontent);
            return true;
        } catch (TikaException e) {
            return false;
        }
    }

  输出结果:spa

测试数据---读取文本内容code