初识lucene

package com.cgm.test;

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

import org.apache.lucene.analysis.standard.StandardAnalyzer;
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.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class HelloLucene {

public void index() {
//Directory deDirectory = new RAMDirectory();
Directory deDirectory = null ;
try {
deDirectory = FSDirectory.open(new File("d:/lucene/index"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(
Version.LUCENE_35));
IndexWriter indexWriter = null;
try {
indexWriter = new IndexWriter(deDirectory, indexWriterConfig);
Document document = null;

File f = new File("D:/example");
for (File file : f.listFiles()) {
document = new Document();
document.add(new Field("content", new FileReader(file)));
document.add(new Field("fileName", file.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
document.add(new Field("path", file.getAbsolutePath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
indexWriter.addDocument(document);
}

} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LockObtainFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (indexWriter != null) {
try {
indexWriter.close();
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}

}



package com.cgm.test;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new HelloLucene().index();
}
}

你可能感兴趣的:(Lucene)