1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package com.matrix.lucene;
import java.io.File; import java.util.ArrayList; import java.util.List;
import org.apache.commons.io.FileUtils; 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.Store; import org.apache.lucene.document.LongField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; 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.util.Version; import org.junit.Test;
public class Index {
@Test public void createIndex() throws Exception { Directory dir = FSDirectory.open(new File("F:\\index")); IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_4_9, new StandardAnalyzer(Version.LUCENE_4_9)); IndexWriter iw = new IndexWriter(dir, conf); File file = new File("F:\\software\\centos\\lucene"); File[] files = file.listFiles(); List<Document> docs = new ArrayList<Document>(); for (File f : files) { TextField content = new TextField("content", FileUtils.readFileToString(f), Store.YES); StringField fileName = new StringField("fileName", f.getName(), Field.Store.YES); LongField modifyTime = new LongField("modifyTime", f.lastModified(), Field.Store.YES); Document doc = new Document(); doc.add(content); doc.add(fileName); doc.add(modifyTime); docs.add(doc); } iw.addDocuments(docs); iw.commit(); iw.close(); } }
|