lucene入门demo学习

           lucene自带的demo需要在命令行下运行,对于初次学习的人来说极为不变。对其demo进行了修改并附加中文注释,希望对喜爱lucene的人有所帮助,lucene的版本是最新的2.4.

           下面是修改后的IndexFiles,可以直接在IDE总运行。代码如下所示:

      

package com.exceljava.lucene;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.demo.FileDocument;
import org.apache.lucene.index.IndexWriter;
/**
* @author xjj email: exceljava@163.com description:建立索引
* @date Jan 5, 2009
*/
public class IndexFiles {
private IndexFiles() {
}
static final File INDEX_DIR = new File("exceljava");
// 指定要索引的目录
static final String DIR_PATH = "d:\\days";
public static void main(String[] args) {
indexWriter(INDEX_DIR,DIR_PATH);
}
/**
* function:索引创建
* @param file
* @param dirPath
* @date Jan 5, 2009
* @time 5:06:17 PM
*/
public static void indexWriter(File file,String dirPath){
// if (INDEX_DIR.exists()) {
// System.out.println(”索引目录’” + INDEX_DIR + “‘已经存在,请先删除该索引”);
// System.exit(1);
// }
final File docDir = new File(dirPath);
if (!docDir.exists() || !docDir.canRead()) {
System.out.println(”文档目录 ‘” + docDir.getAbsolutePath()
+ “‘不存在或不能读写”);
System.exit(1);
}
long start =System.currentTimeMillis();
try {
IndexWriter writer = new IndexWriter(file,
new StandardAnalyzer(), //
true,//这里的true表示重新建立索引,如果存在也将覆盖。false则表示如果存在索引则在现有基础上进行拓展
IndexWriter.MaxFieldLength.LIMITED);
System.out.println(”索引’” + INDEX_DIR + “‘…”);
indexDocs(writer, docDir);
//合并小索引文件并进行优化
writer.optimize();
writer.close();
long end =System.currentTimeMillis();
System.out.println(”共耗时:” + (end - start)+ “毫秒”);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* function:检索目录,并调用创建索引函数进行索引创建,支持对目录内嵌目录进行检索
* @param writer
* @param file
* @throws IOException
* @date Jan 5, 2009
* @time 4:49:45 PM
*/
static void indexDocs(IndexWriter writer, File file) throws IOException {
if (file.canRead()) {
if (file.isDirectory()) {
String[] files = file.list();
if (files != null) {
//检索内嵌目录
for (int i = 0; i < files.length; i++) {
indexDocs(writer, new File(file, files[i]));
//new File(file, files[i])通过父路径file和子路径files[i]创建文件
}
}
} else {
System.out.println(”添加索引文件: ” + file);
try {
//向索引中添加构造好的文档
writer.addDocument(FileDocument.Document(file));
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}
}
}
}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值