lucene 索引非txt文档 (pdf word rtf html xml)

搜索要首先要索引,索引的话最简单的方式是索引txt文件,上文已经介绍了。这里介绍一下一些其它格式的文档的索引,例如ms word ,pdf ,rtf等。
索引方法:就是先把各种文档先转化成纯文本再索引,所以关键在转换上。幸好java世界中有太多的开源工程,很多都可以拿来直接使用。下边分别介绍一下:
写在所有之前:下边所有介绍中的is参数都是inputStream,就是被索引的文件。
word文档:
把word文档转换成纯文本的开源工程可以使用:POI 或者TextMining
POI的使用方法:
 WordDocument wd = new WordDocument(is);
      StringWriter docTextWriter 
= new StringWriter();
      wd.writeAllText(
new PrintWriter(docTextWriter));
      docTextWriter.close();
      bodyText 
= docTextWriter.toString();
TextMining的使用方法更简单:
bodyText = new WordExtractor().extractText(is);

PDF文档:
转换PDF文档可以使用的类库是PDFbox
COSDocument cosDoc = null;
   PDFParser parser = new PDFParser(is);
    parser.parse();
cosDoc 
= parser.getDocument()
if (cosDoc.isEncrypted()) {
        DecryptDocument decryptor 
= new DecryptDocument(cosDoc);
        decryptor.decryptDocument(password);
 }
PDFTextStripper stripper 
= new PDFTextStripper();
String docText 
= stripper.getText(new PDDocument(cosDoc));
RTF文档:
rtf的转换则在javax中就有
DefaultStyledDocument styledDoc = new DefaultStyledDocument();
new RTFEditorKit().read(is, styledDoc, 0);
      String bodyText 
= styledDoc.getText(0, styledDoc.getLength());
这样就可以索引各种格式的文本了

html和xml的处理方法同样
不同的是html的可用类库是:JTidy
Xml可用的类库是SAX和digester
原文地址:https://www.cnblogs.com/pony/p/1486280.html