我开始学习使用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
(也已弃用)。这会导致溢出吗?如果是这样,我应该使用什么呢?
答案 0 :(得分:3)
不,不要创建自己的FSDirectory匿名子类!改为使用FSDirectory.open,或实例化Lucene提供的FSDirectory的具体子类,如NIOFSDirectory(但在这种情况下,您必须仔细阅读所选实现的Javadoc,每个都有特定于操作系统的陷阱)。即使在版本3.0中,Lucene也不会期望您创建自己的FSDirectory子类。