今天学习孔浩lucene的视频第一集,跟着做了一遍,运行时候报错,原因是视频中打开文件夹的那段代码出错,于是就自己封装了个工具类
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* 方便使用lucene的工具包
* @author
* @date 2016-8-18 上午11:34:04
* @company
* @version 1.0
* @copyright copyright (c) 2016
*/
public class LuceneUtils {
/**
* 获取文件夹下的所有满足后缀的文件<br><br>
* @author
* @date 2016-8-18 上午11:43:30<br>
* @param dirName 要处理的文件夹名
* @param suffix 文件后缀,如:txt,avi
* @return<br>
*/
public static File[] queryTxtFile(String dirName, String suffix){
File dir = new File(dirName);
File[] files = dir.listFiles();
String matchedFileName = "";
if(files != null){
for(int i = 0; i < files.length; i++ ){
String fileName = files[i].getName();
String[] suffixName = fileName.split("\\.");
if(suffixName[suffixName.length - 1].matches(suffix)){
matchedFileName = matchedFileName + fileName +"\\|"; //记录后缀满足的文件名
}
}
}
if(matchedFileName != ""){
String[] names = matchedFileName.split("\\|"); //把满足后缀的文件名分割开,创建文件File
File[] resultFiles = new File[names.length];
for(int i = 0; i < names.length; i ++){
resultFiles[i] = new File(dirName + "/" + names[i]);
}
return resultFiles;
}else{
return null;
}
}
}
lucene创建索引的那段代码修改完毕后是
public static void main(String[] args) {
//1.创建Directory
//Directory directory = new RAMDirectory(); //建立在内存中
Directory directory = null;
//2.创建IndexWriter
IndexWriterConfig iwc = null;
IndexWriter writer = null;
try {
directory = FSDirectory.open(new File("d:/lucene_test/lucene01"));
iwc = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35));
writer = new IndexWriter(directory, iwc);
//3.创建Document对象
Document doc = new Document();
//4.为Document添加Field
File[] files = LuceneUtils.queryTxtFile("d:/lucene_test", "txt");
for(int i = 0; i < files.length; i++){
doc = new Document();
doc.add(new Field("content", new FileReader(files[i])));
doc.add(new Field("filename", files[i].getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("path", files[i].getAbsolutePath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
writer.addDocument(doc);
}
File f = new File("d:/lucene_test");
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LockObtainFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(writer != null){
try {
writer.close();
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
GBK编码考过来有乱码,下次再整理