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()));??
?????????????????
?????????? //以下兩句只能取一句,前者是索引不存儲(chǔ),后者是索引且存儲(chǔ)
?????????? //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();
?????? }
??? }
???
??? /**
??? ?*從文本文件中讀取內(nèi)容
??? ?* @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中包含關(guān)鍵字"holen"和"java"
?????? if(temp.insertRecords(dbpath,"e:\\lucene\\holen1.txt")==1){
?????????? System.out.println("add file1 succ");
?????? }
?????? //holen2.txt中包含關(guān)鍵字"holen"和"chen"
?????? if(temp.insertRecords(dbpath,"e:\\lucene\\holen2.txt")==1){
?????????? System.out.println("add file2 succ");
?????? }??
??? }
}
|