package org.lucene.createindex;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;
public class CreateIndex {
public static void main(String[] args) throws CorruptIndexException,
LockObtainFailedException, Exception {
// 1.创建索引的存放地
File index = new File("C:\\suoyin");
IKAnalyzer ikAnalyzer = new IKAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,ikAnalyzer).setOpenMode(OpenMode.CREATE);
IndexWriter indexWriter = new IndexWriter(FSDirectory.open(index), iwc);
//2.获取本地文件夹中的文件
File[] textFiles = new File("C:\\source").listFiles();
//3循环文件判断是不是.txt文件
for (int j = 0; j < textFiles.length; j++) {
if (textFiles[j].isFile() && textFiles[j].getName().endsWith(".txt"))
{
//4如果是的话就读取里面的文本,并且new一个document(Document document = new Document();)
String fileContent = FileReaderAll(textFiles[j].getCanonicalPath(),"GBK");
//5new Document()新建一个文档
Document document = new Document();
Field FieldBody = new Field("fileContent", fileContent, Field.Store.YES, Field.Index.ANALYZED);
document.add(FieldBody);
Field fileName = new Field("mm", textFiles[j].getName(), Field.Store.NO, Field.Index.NOT_ANALYZED);
document.add(fileName);
//6.最后往索引文件夹里面写索引
indexWriter.addDocument(document);
}
}
System.out.println("创建索引成功");
indexWriter.close(); // 这里不关闭建立索引会失败
}
private static String FileReaderAll(String FileName, String charset) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(FileName), charset));
String line = new String();
String temp = new String();
while ((line = reader.readLine()) != null)
{
temp += line;
}
reader.close();
return temp;
}
}
lucene创建索引
最新推荐文章于 2022-05-28 16:27:58 发布