利用lucene对PDF文本进行内容的解析

/** 这段代码的功能是利用PDFBox.zip的包* 利用lucene对PDF文本进行内容的解析* 读取pdf文件的内容。然后重新的写入到同名的.txt文件中

* */

结果截图:

package pdfbox;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.net.MalformedURLException;import java.net.URL;import org.pdfbox.pdmodel.PDDocument;import org.pdfbox.util.PDFTextStripper;public class PdfBox {public PdfBox() {// TODO Auto-generated constructor stub}public void geText(String file) throws Exception{//是否排序boolean sort = false;//pdf名称String pdfFile = file;//输入文本文件名称String textFile = null;//设置编码方式String encoding = "UTF-8";//开始提取页数int startPage = 1;//结束提取页数int endPage = Integer.MAX_VALUE;//文件输入流,,生成文本文件Writer output = null;//内存中存储的PDF DocumentPDDocument document = null;try{try{//首先当做一个URL来装载文件,//如果得到异常再从本地文件系统去装载文件URL url = new URL(pdfFile);document = PDDocument.load(url);//获取PDF的文件名String fileName = url.getFile();//原来的PDF名称来命名新产生的txt文件if(fileName.length( ) > 4){File outputFile = new File(fileName.substring(0, fileName.length() – 4) + ".txt");textFile = outputFile.getName();}}catch(MalformedURLException r){//如果作为URl装载到异常则从文件系统装载document = PDDocument.load(pdfFile);if(pdfFile.length() > 4){textFile = pdfFile.substring(0, pdfFile.length() – 4) + ".txt";}}//文件输入流,写入文件到textFileoutput = new OutputStreamWriter(new FileOutputStream(textFile), encoding);//PDFTextStripprt来提取文件PDFTextStripper stripper = null;stripper = new PDFTextStripper();//设置是否排序stripper.setSortByPosition(sort);//设置起始页stripper.setStartPage(startPage);//设置结束页stripper.setEndPage(endPage);//调用PDFTextStripper的writerText提取并输出stripper.writeText(document, output);}finally{//关闭输出流if(output != null)output.close();}//关闭PDF Documentif(document != null){document.close();}}public static void main(String[] args) {// TODO Auto-generated method stubPdfBox test = new PdfBox();try{//获取E:\Lucene项目下的C语言代码.pdf的内容test.geText("E:\\Lucene项目\\C语言代码.pdf");}catch(Exception e){e.printStackTrace();}}}

当你能梦的时候就不要放弃梦

利用lucene对PDF文本进行内容的解析

相关文章:

你感兴趣的文章:

标签云: