转载自:http://blog.csdn.net/hustsdy/article/details/4133033
万事开头难,在开始研究lucene就如猫吃乌龟,不知从何下手。承蒙高手点化,有所心得,记之。
对于java一样面向对象的语言来说,几乎每一个java源文件都是有一个个类组成的,即使在知道lucene的工作流程之后,也不好下手,尤其对于对象之间的调用,很是迷茫。
最开始试想寻找lucene的入口点可以从main函数开始,但是,在执行main函数时,并没有出现自己想要的结果,甚是痛苦,不得不求助于人。最终还是得到了满意的解决方案。
解决方案:
新建一个test类,把整个索引的过程从头到尾走一遍,然后用单步调试跟踪,直到调用涉及底层方法为止。
新建类的源代码如下:
- package test;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStreamReader;
- import java.io.Reader;
- import java.util.Date;
- import org.apache.lucene.analysis.standard.StandardAnalyzer;
- import org.apache.lucene.document.Document;
- import org.apache.lucene.document.Field;
- import org.apache.lucene.index.IndexWriter;
- public class LuceneIndex {
- public static void main(String[] args) throws Exception {
- // 声明一个对象
- LuceneIndex indexer = new LuceneIndex();
- // 建立索引
- Date start = new Date();
- System.out.println(start);
- indexer.writeToIndex();
- Date end = new Date();
- System.out.println(end);
- System.out.println("建立索引用时" + (end.getTime() - start.getTime()) + "毫秒");
- indexer.close();
- }
- public LuceneIndex() {
- try {
- writer = new IndexWriter(Constants.INDEX_STORE_PATH,
- new StandardAnalyzer(), true);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- // 索引器
- private IndexWriter writer = null;
- // 将要建立索引的文件构造成一个Document对象,并添加一个域"content"
- private Document getDocument(File f) throws Exception {
- Document doc = new Document();
- FileInputStream is = new FileInputStream(f);
- Reader reader = new BufferedReader(new InputStreamReader(is));
- // doc.add(Field.Text("contents", reader));
- doc.add(new Field("contents",reader));
- // doc.add(new Field("path", f.getAbsolutePath()));
- return doc;
- }
- public void writeToIndex() throws Exception {
- File folder = new File(Constants.INDEX_FILE_PATH);
- if (folder.isDirectory()) {
- String[] files = folder.list();
- for (int i = 0; i < files.length; i++) {
- File file = new File(folder, files[i]);
- Document doc = getDocument(file);
- System.out.println("正在建立索引 : " + file + "");
- writer.addDocument(doc);
- }
- }
- }
- public void close() throws Exception {
- writer.close();
- }
- }
双击代码左栏,设置断点,
然后再按F11进入debug状态,在这个过程中有几个快捷键要知道
F5:step into进入方法体
F6:step over跳过方法体
F7:step return返回上一步
了解这几个快捷键有助于加快调试过程。
这样多次使用F5可以看到对象之间的调用。为了更好的研究代码,觉得有款软件很好
Source Insight 推荐给大家
在我上传资源上面有
http://download.csdn.net/source/1256356
是英文版的,其实英文版面挺好用的,O(∩_∩)O
自己也是刚刚研究源代码,有什么不足之处还望各位斧正。
看代码是个很痛苦的过程,最好在你心静的时候研究,在晚上夜深人静的时候看更好
有时候就在想,如果晚上能把自己与心仪的女孩子聊天的那股热情用到看代码上面,小小的一个lucene岂不是区区小菜