0

我开始学习使用 Lucene,并首先尝试从我找到的一本书中为 Indexer 类编译示例。该类如下所示:

public class Indexer 
{

private IndexWriter writer;

public static void main(String[] args) throws Exception 
{
    String indexDir = "src/indexDirectory";
    String dataDir = "src/filesDirectory";

    long start = System.currentTimeMillis();
    Indexer indexer = new Indexer(indexDir);
    int numIndexer = indexer.index(dataDir);
    indexer.close();
    long end = System.currentTimeMillis();

    System.out.println("Indexarea a " + numIndexer + " fisiere a durat "
            + (end - start) + " milisecunde");
}


public Indexer(String indexDir) throws IOException
{
    Directory dir = new FSDirectory(new File(indexDir), null) {};

    writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_35), true, IndexWriter.MaxFieldLength.UNLIMITED);
}


public void close() throws IOException
{
    writer.close();
}


public int index(String dataDir) throws Exception
{
    File[] files = new File(dataDir).listFiles();

    for (int i=0;i<files.length; i++)
    {
        File f = files[i];

        if (!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead() && acceptFile(f))
        {
            indexFile(f);
        }
    }

    return writer.numDocs();
}


protected boolean acceptFile(File f)
{
    return f.getName().endsWith(".txt");
}


protected Document getDocument(File f) throws Exception
{
    Document doc = new Document();
    doc.add(new Field("contents", new FileReader(f)));
    doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));

    return doc;
}


private void indexFile(File f) throws Exception
{
    System.out.println("Indexez " + f.getCanonicalPath());
    Document doc = getDocument(f);
    if (doc != null)
    {
        writer.addDocument(doc);
    }
}

}

当我运行它时,我得到

Exception in thread "main" java.lang.StackOverflowError
at org.apache.lucene.store.FSDirectory.openInput(FSDirectory.java:345)
at org.apache.lucene.store.Directory.openInput(Directory.java:143)

并且这样持续了几十次。

我的班级的构造函数

public Indexer(String indexDir) throws IOException
{
    Directory dir = new FSDirectory(new File(indexDir), null) {};

    writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_35), true, IndexWriter.MaxFieldLength.UNLIMITED);
}

有一个IndexWriter已弃用的调用(因为本书是为 lucene 3.0.0 编写的)并使用此方法 IndexWriter.MaxFieldLength.UNLIMITED(也已弃用)。这会导致溢出吗?如果是这样,我应该改用什么?

4

1 回答 1

3

不,不要创建自己的 FSDirectory 匿名子类!改用 FSDirectory.open,或实例化 Lucene 提供的 FSDirectory 的具体子类,如 NIOFSDirectory(但在这种情况下,您必须仔细阅读所选实现的 Javadoc,每个都有特定于操作系统的缺陷)。即使在 3.0 版中,Lucene 也从未期望您创建自己的 FSDirectory 子类。

于 2012-04-04T11:05:20.153 回答