/**
* 创建索引
*/
@Test
public void index(){
Directory directory = null;
try {
// FSDirectory自动选取一种合适的读取方式,FileSystems.getDefault().getPath("d:/luceneTest")
// nio获取路径的方式,我也不太理解哈哈
directory = FSDirectory.open(FileSystems.getDefault().getPath("d:/luceneTest"));
} catch (IOException e1) {
e1.printStackTrace();
}
// 创建iw的配置,选用标准分词器
IndexWriterConfig iwc = new IndexWriterConfig(new StandardAnalyzer());
IndexWriter iw = null;
try {
// 将路径和配置传入iw
iw = new IndexWriter(directory, iwc);
// 清除之前存在的索引
iw.deleteAll();
Document doc = null;
// 创建被索引文档file
File file = new File("d:/lucene");
for(File f : file.listFiles()){
// TextField应该是是否存储所有内容
doc = new Document();
doc.add(new Field("content",new FileReader(f), TextField.TYPE_NOT_STORED));
doc.add(new Field("filename",f.getName(), TextField.TYPE_STORED));
doc.add(new Field("filepath",f.getAbsolutePath(), TextField.TYPE_STORED));
iw.addDocument(doc);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(iw!=null)iw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
学习http://blog.csdn.net/zhongweijian/article/details/8452999