zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    

      输出结果:

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

  • 相关阅读:
    基于u盘身份验证
    新的一年开始了~!
    asp.net的条形码
    windows phone (21) Grid元素的Background和Clip
    windows phone (19) 深入了解TextBlock
    windows phone (25) Canvas元素B
    windows phone (20) Image元素
    windows phone (22) 隐藏元素
    windows phone (26) ApplicationBar应用程序栏
    windows phone (27) 基础Button
  • 原文地址:https://www.cnblogs.com/hww-2429/p/11550425.html
Copyright © 2011-2022 走看看