packagecom.holen.part1;
importjava.io.File;
importjava.io.FileReader;
importjava.io.Reader;
importorg.apache.lucene.analysis.standard.StandardAnalyzer;
importorg.apache.lucene.document.Document;
importorg.apache.lucene.document.Field;
importorg.apache.lucene.index.IndexWriter;
/**
* @authorHolenChen
*记录加载
*/
public
classInsertRecords{
publicInsertRecords(){
}
publicintinsertRecords(Stringdbpath,Filefile){
intreturnValue=0;
try{
IndexWriterindexWriter
= newIndexWriter(dbpath,newStandardAnalyzer(),false);
this.addFiles(indexWriter,file);
returnValue=1;
}catch(Exceptionex){
ex.printStackTrace();
}
returnreturnValue;
}
/**
*传入需加载的文件名
* @paramfile
* @return
*/
publicintinsertRecords(Stringdbpath,Stringfile){
returnthis.insertRecords(dbpath,newFile(file));
}
publicvoidaddFiles(IndexWriterindexWriter,Filefile){
Documentdoc= newDocument();
try{
doc.add(Field.Keyword("filename",file.getName()));
//以下两句只能取一句,前者是索引不存储,后者是索引且存储
//doc.add(Field.Text("content",new FileReader(file)));
doc.add(Field.Text("content",this.chgFileToString(file)));
indexWriter.addDocument(doc);
indexWriter.close();
}catch(Exceptionex){
ex.printStackTrace();
}
}
/**
*从文本文件中读取内容
* @paramfile
* @return
*/
publicStringchgFileToString(Filefile){
StringreturnValue= null;
StringBuffersb= newStringBuffer();
char[]c= newchar[4096];
try{
Readerreader= newFileReader(file);
intn=0;
while(true){
n=reader.read(c);
if(n>0){
sb.append(c,0,n);
}else{
break;
}
}
reader.close();
}catch(Exceptionex){
ex.printStackTrace();
}
returnValue=sb.toString();
returnreturnValue;
}
publicstaticvoidmain(String[]args){
InsertRecordstemp= newInsertRecords();
Stringdbpath="e:\\lucene\\holendb";
//holen1.txt中包含关键字"holen"和"java"
if(temp.insertRecords(dbpath,"e:\\lucene\\holen1.txt")==1){
System.out.println("add file1 succ");
}
//holen2.txt中包含关键字"holen"和"chen"
if(temp.insertRecords(dbpath,"e:\\lucene\\holen2.txt")==1){
System.out.println("add file2 succ");
}
}
}
|