We built a folder under the D-Disk called Lucene,lucene two more folders, a call example, a call index01. Example folder under three TXT files, a.txt content for Hello java,b.txt content for hello lucene,c.txt content for Hello Hadoop.
Packagecom.amazing;ImportJava.io.File;ImportJava.io.FileReader;Importjava.io.IOException;ImportOrg.apache.lucene.analysis.standard.StandardAnalyzer;Importorg.apache.lucene.document.Document;ImportOrg.apache.lucene.document.Field;Importorg.apache.lucene.index.CorruptIndexException;ImportOrg.apache.lucene.index.IndexWriter;ImportOrg.apache.lucene.index.IndexWriterConfig;Importorg.apache.lucene.store.Directory;Importorg.apache.lucene.store.FSDirectory;Importorg.apache.lucene.util.Version; Public classHelloLucene { Public voidCreateIndex () {IndexWriter writer=NULL; Try{Directory directory= Fsdirectory.open (NewFile ("D:" +file.separator+ "Lucene" +file.separator+ "index01")); Indexwriterconfig IWC=NewIndexwriterconfig (version.lucene_35,NewStandardAnalyzer (version.lucene_35)); Writer=NewIndexWriter (DIRECTORY,IWC); Document Doc=NULL; File F=NewFile ("D:" +file.separator+ "Lucene" +file.separator+ "Example"); for(File file:f.listfiles ()) {doc=NewDocument (); Doc.add (NewField ("Content",Newfilereader (file)); Doc.add (NewField ("filename", File.getname (), field.store.yes,field.index.not_analyzed)); Doc.add (NewField ("Path", File.getabsolutepath (), field.store.yes,field.index.not_analyzed)); Writer.adddocument (DOC); } } Catch(IOException e) {e.printstacktrace (); } finally{ if(Writer! =NULL){ Try{writer.close (); } Catch(corruptindexexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } } } }}
To run the test class:
Package com.amazing; Import org.junit.Test; Public class testlucene { @Test publicvoid Testcreateindex () { new HelloLucene (); Hl.createindex (); }}
Some files appear under folder index01:
LUCENE-01: Creating an Index