搜索要首先要索引,索引的話最簡單的方式是索引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