JAVA读取PDF、WORD文档实例代码
读取PDF文件jar引用
org.apache.pdfbox pdfbox1.8.13
读取WORD文件jar引用
org.apache.poi poi-scratchpad3.16-beta1 org.apache.poi poi3.16-beta1
读取WORD文件方法
/**
*
*@Title:getTextFromWord
*@Description:读取word
*@paramfilePath
*文件路径
*@return:String读出的Word的内容
*/
publicstaticStringgetTextFromWord(StringfilePath){
Stringresult=null;
Filefile=newFile(filePath);
FileInputStreamfis=null;
try{
fis=newFileInputStream(file);
@SuppressWarnings("resource")
WordExtractorwordExtractor=newWordExtractor(fis);
result=wordExtractor.getText();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(fis!=null){
try{
fis.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnresult;
}
读取PDF文件方法
/**
*
*@Title:getTextFromPdf
*@Description:读取pdf文件内容
*@paramfilePath
*@return:读出的pdf的内容
*/
publicstaticStringgetTextFromPdf(StringfilePath){
Stringresult=null;
FileInputStreamis=null;
PDDocumentdocument=null;
try{
is=newFileInputStream(filePath);
PDFParserparser=newPDFParser(is);
parser.parse();
document=parser.getPDDocument();
PDFTextStripperstripper=newPDFTextStripper();
result=stripper.getText(document);
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(is!=null){
try{
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(document!=null){
try{
document.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnresult;
}
希望本篇实例代码可以帮到您