温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JAVA读取PDF、WORD文档实例代码

发布时间:2020-09-05 17:05:02 来源:脚本之家 阅读:139 作者:wbb 栏目:编程语言

读取PDF文件jar引用

<dependency>
  <groupid>org.apache.pdfbox</groupid>
  pdfbox</artifactid>
  <version>1.8.13</version>
</dependency>

读取WORD文件jar引用

<dependency>
  <groupid>org.apache.poi</groupid>
  poi-scratchpad</artifactid>
  <version>3.16-beta1</version>
</dependency>
<dependency>
  <groupid>org.apache.poi</groupid>
  poi</artifactid>
  <version>3.16-beta1</version>
</dependency>

读取WORD文件方法

/**
   * 
   * @Title: getTextFromWord
   * @Description: 读取word
   * @param filePath
   *      文件路径
   * @return: String 读出的Word的内容
   */
  public static String getTextFromWord(String filePath) {
    String result = null;
    File file = new File(filePath);
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(file);
      @SuppressWarnings("resource")
      WordExtractor wordExtractor = new WordExtractor(fis);
      result = wordExtractor.getText();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }

读取PDF文件方法

/**
 * 
 * @Title: getTextFromPdf
 * @Description: 读取pdf文件内容
 * @param filePath
 * @return: 读出的pdf的内容
 */
public static String getTextFromPdf(String filePath) {
  String result = null;
  FileInputStream is = null;
  PDDocument document = null;
  try {
    is = new FileInputStream(filePath);
    PDFParser parser = new PDFParser(is);
    parser.parse();
    document = parser.getPDDocument();
    PDFTextStripper stripper = new PDFTextStripper();
    result = stripper.getText(document);
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  } finally {
    if (is != null) {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    if (document != null) {
      try {
        document.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  return result;
}

希望本篇实例代码可以帮到您

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI