apache tika检测文件是否损坏

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

将上传文件至服务器,进行解析文件时,经常需要判断文件是否损坏。我们可以使用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包冲突时可以引入如下:

<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异常

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

  • 执行过程:
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;
        }
    }

  输出结果:

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

 

posted @ 2019-09-20 11:53  随遇而安~~~  阅读(1082)  评论(0编辑  收藏  举报