Lucene学习-创建索引(二)

为指定文件夹下的所有文件创建索引

用到先前的辅助类:FileText.java和FileList.java,创建LoopIndexer.java代码如下:

 

 package index; import index.FileList; import index.FileText; import java.io.File; import java.io.IOException; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.analysis.standard.StandardAnalyzer; public class LoopIndexer { public static void main(String[] args) throws IOException { // 设定索引存放的路径 String indexPath = "F:/DocumentIndex"; // 创建IndexWriter IndexWriter writer = new IndexWriter(indexPath, new StandardAnalyzer()); String[] files = FileList.getFiles("doc"); int num = files.length; // 循环构建,将Doc目录下的文件内容进行提取,封装到Document中 for (int i = 0; i < num; i++) { // 创建Document Document doc = new Document(); File f = new File(files[i]); // 创建Field-name String name = f.getName(); Field field = new Field("name", name, Field.Store.YES, Field.Index.TOKENIZED); // 添加field doc.add(field); // 创建Field-content String content = FileText.getText(f); field = new Field("content", content, Field.Store.YES, Field.Index.TOKENIZED); // 添加field doc.add(field); // 创建Field-path String path = f.getPath(); field = new Field("path", path, Field.Store.YES, Field.Index.TOKENIZED); // 添加field doc.add(field); System.out.println("File:" + name + " Indexed!"); // 添加 document writer.addDocument(doc); // 关闭IndexWriter writer.close(); // 提示 System.out.println("Loop File Index Created!"); } } }  

 

你可能感兴趣的:(Lucene学习-创建索引(二))