当前位置: 代码迷 >> Web前端 >> lucene3.0 例1
  详细解决方案

lucene3.0 例1

热度:502   发布时间:2012-11-22 00:16:41.0
lucene3.0 例一

package com.lucene;

import java.io.File;
import java.io.IOException;


import org.apache.commons.io.FileUtils;
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.document.Field.Index;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;

public class LuceneTxt{
??? @Test
??? public void testWriter() throws Exception{
??? ??? // 获取工程路径
??? ??? String projectPath = System.getProperty("user.dir");
??? ??? // 获取文件资源路径
??? ??? File dataDir = new File(projectPath, "txt");
??? ??? if (!dataDir.exists() || !dataDir.isDirectory()) {
??? ??? ??? return;
??? ??? }
??? ??? // 确定数据源
??? ??? File[] dataFiles = dataDir.listFiles();
??? ??? if (dataFiles.length < 1) {
??? ??? ??? return;
??? ??? }
??? ??? // crate indexWriter
??? ??? IndexWriter indexWriter = null;
??? ??? try {
??? ??? ??? // get index dirPath
??? ??? ??? File indexDir = new File(projectPath, "index");
??? ??? ??? if (!indexDir.exists()) {
??? ??? ??? ??? indexDir.mkdir();
??? ??? ??? }
//??? ??? ??? Directory directory = new RAMDirectory();
??? ??? ??? Directory directory = FSDirectory.open(indexDir);
??? ??? ??? Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
??? ??? ??? indexWriter = new IndexWriter(directory, analyzer, true,
??? ??? ??? ??? ??? IndexWriter.MaxFieldLength.LIMITED);
??? ??? ??? //create document add to IndexWriter
??? ??? ??? for(File dataFile:dataFiles){
??? ??? ??? ??? Document document = new Document();
??? ??? ??? ??? //create Field add to Document
??? ??? ??? ??? document.add(new Field("fileContent",FileUtils.readFileToString(dataFile, "gbk"),Field.Store.YES,Field.Index.ANALYZED));
??? ??? ??? ???
??? ??? ??? ???
??? ??? ??? ??? indexWriter.addDocument(document);
??? ??? ??? }
??? ??? ??? indexWriter.optimize();
??? ??? } catch (Exception e) {
??? ??? ??? e.printStackTrace();
??? ??? } finally {
??? ??? ??? if (indexWriter!=null) {
??? ??? ??? ??? indexWriter.close();
??? ??? ??? }
??? ??? }

??? }
??? private void testSearch() {
??? ??? // create indexSearch

??? }
}