import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Date;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
public class TextFileIndexer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO 自动生成方法存根
File fileDir=new File("D:\\chenzk\\lucene");
Analyzer luceneAnalyzer=new StandardAnalyzer();
//创建一个类StandardAnalyzer的一个实例,这个实例是从文本中提取索引项的
File indexDir = new File("C:\\luceneIndex");
IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,true);
//第一个参数是存储索引文件的路径,第二个参数是指定了在索引的过程中使用什么样的分词器,最后一个参数是一个布尔的参数如果
//为真表示要创建一个新的索引,如果值为假表示打开一个已经存在的索引
File [] textFiles=fileDir.listFiles();
long startTime=new Date().getTime();
//add documents to the index
for(int i=0;i<textFiles.length;i++)
{
if(textFiles[i].isFile()&&textFiles[i].getName().endsWith(".txt"))
{ //只要你能将要索引的文件转化成文本格式lucene就能为你的文档建立索引
System.out.println("File "+textFiles[i].getCanonicalPath()+" is being indexed");
Reader textReader=new FileReader(textFiles[i]);
//以下是如何添加一个文档到索引文件中
Document document=new Document();// 它是由一个或者多个Field组成,我们可以把它想象是一个实际文档
//实际的Field是实际文档一些属性,
document.add(Field.Text("content",textReader));//域的名称我们需要索引的文本文件的内容
document.add(Field.Text("path", textFiles[i].getPath()));//我们需要索引的文本文件的路径
indexWriter.addDocument(document);
}
}
indexWriter.optimize();
indexWriter.close();//当我们把文档添加到索引中后,不要忘记关闭索引,这样才保证Lucene把添加的文档写回到硬盘上。
long endTime=new Date().getTime();
System.out.println("It took "+(endTime-startTime)+" millseconds to create an index for the files in the directory "+fileDir.getPath()) ;
}
}
File D:\chenzk\lucene\1.txt is being indexed
File D:\chenzk\lucene\2.txt is being indexed
File D:\chenzk\lucene\3.txt is being indexed
File D:\chenzk\lucene\segments.txt is being indexed
It took 187 millseconds to create an index for the files in the directory D:\chenzk\lucene
请大家提供宝贵的意见!谢谢