用Lucene创建PDF文档的索引时,需要引入第三方的PDFBox包,目前PDFBox的最新版本为v-0.8.0,其创建过程的主要代码如下:
添加Field.
Document document = LucenePDFDocument.getDocument(fileName); ;
document.add(new Field(FIELD_PATH,fileName.getPath(),Field.Store.YES, Field.Index.UN_TOKENIZED));
document.add(new Field(FIELD_CONTENT,readPDF(fileName.getPath()), Field.Store.YES, Field.Index.TOKENIZED));
读取PDF文件
public String readPDF(String filePath) throws Exception {
StringBuffer content = new StringBuffer();
FileInputStream fis = new FileInputStream(filePath);
PDFParser parser = new PDFParser(fis);
parser.parse();
PDDocument pdd = parser.getPDDocument();
PDFTextStripper ts = new PDFTextStripper();
content.append(ts.getText(pdd));
pdd.close();
fis.close();
return content.toString().trim();
}
添加document.
IndexWriter indexWriter = new IndexWriter(indexDir,new StandardAnalyzer(),true);
indexWriter.addDocument(document);
Okay,如果有其他格式的文件,比如html,word,excel,mp3等文件格式,也需要对应的第三方包的支持,索引过程大致一样,就不在此赘述.
本Blog文章除特别声明之外皆为原创文章,欢迎转载,转载请注明: 转载自JSSAY'S BLOG
本文链接地址: http://www.jssay.com/blog/index.php/2009/11/09/lucene%e7%b4%a2%e5%bc%95pdf%e6%96%87%e6%a1%a3/