一:处理PDF文档
处理PDF文档需要引用pdfbox-app-1.8.7.jar的jar包(ps:版本应该没有具体要求)。
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.util.PDFTextStripper; private static String getPDFText(File file){ PDDocument document; String text = ""; try { document = PDDocument.load(file); PDFTextStripper stripper = new PDFTextStripper(); text = stripper.getText(document); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return text; }
二:处理doc文档
处理doc文档需要引入poi-3.10.1-20140818.jar和poi-scratchpad-3.10.1-20140818.jar
import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Range; public String getDocContent(File docFile){ FileInputStream docFis; String text = null; try { docFis = new FileInputStream(docFile); HWPFDocument doc = new HWPFDocument(docFis); Range rang = doc.getRange(); text = rang.text(); docFis.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return text; }
三:处理docx文档
处理docx文档需要引入poi-ooxml-3.10.1-20140818.jar和poi-ooxml-schemas-3.10.1-20140818.jar以及xmlbeans-2.3.0.jar(ps:使用的XWPFWordExtractor()中用到了xmlbeans-2.3.0.jar中的类。)
import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFDocument; public String getDocxContent(File docxFile){ FileInputStream docxFis; String text = null; try { docxFis = new FileInputStream(docxFile); XWPFDocument docx = new XWPFDocument(docxFis); XWPFWordExtractor docxExtractor = new XWPFWordExtractor(docx); text = docxExtractor.getText(); docxFis.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return text; }