2,760
社区成员
发帖
与我相关
我的任务
分享
public class IndexProcesser {
//成员变量,存储创建的索引文件的位置
private String INDEX_STORE_PATH = "D:\\java_workspace\\Index";
//创建索引
public void createIndex(String inputDir) throws IOException{
Directory dir = FSDirectory.open(new File(INDEX_STORE_PATH));
try {
Analyzer luceneAnalyzer = new StandardAnalyzer(Version.LUCENE_31);
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_31, luceneAnalyzer);
IndexWriter writer = new IndexWriter(dir,indexWriterConfig);
File filesDirFile = new File(inputDir);
//取得所有需要建立索引的文件数组
File[] files = filesDirFile.listFiles();
//遍历数组
for(int i=0; i<files.length; i++){
//获取文件名
String fileName = files[i].getName();
//判断文件是否是txt类型的文件
if(fileName.substring(fileName.lastIndexOf(".")).equals(".txt")){
//创建一个新的Document
Document doc = new Document();
//为文件名创建一个Field
Field field1 = new Field("name", files[i].getName(),Field.Store.YES,Index.ANALYZED);
Field field2 = new Field("content", loadFileToString(new File(files[i].getPath())),Field.Store.YES,Index.ANALYZED);
doc.add(field1);
doc.add(field2);
//把Document加入IndexWriter
writer.addDocument(doc);
}
}
writer.commit();
//关闭IndexWrite
writer.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 从文件中把内容读出,单个文件内的所有内容放在一个String中返回
*/
public String loadFileToString(File file){
try {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuffer sbBuffer = new StringBuffer();
String line = br.readLine();
while(line!=null){
sbBuffer.append(line);
line=br.readLine();
}
br.close();
return sbBuffer.toString();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
}