lucene创建索引

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; 
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值