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;
            }
        }
    

      输出结果:

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

  • 相关阅读:
    Win10 anaconda python3.6 安装pcap
    跨平台 GUI可视化 网络调试工具
    参考文献相关概念
    linux压缩和解压缩命令大全[转]
    PowerShell 惠普打印机双面驱动自动设置已安装
    CentOS7 一键安装KMS服务【整理】
    pdf转word OCR
    CentOS7 MySQL
    PDF文件比对工具
    pdf文件中截取eps图片并压缩
  • 原文地址:https://www.cnblogs.com/hww-2429/p/11550425.html
Copyright © 2011-2022 走看看