【问题标题】:How to make sure that Lucene leave the file after indexing?如何确保 Lucene 在索引后离开文件?
【发布时间】:2013-10-09 04:00:54
【问题描述】:

我正在使用 Lucene 来索引 XML 文件。文件进入输入目录,被索引并移动到输出目录。

在某些情况下它工作正常,但对于少数文件它会失败。

当我尝试使用 Windows 命令提示符 ren 文件时,它说文件已在使用中,这告诉我 java 进程仍然连接到文件。

有人可以帮助我确保 Lucene java 进程在索引后保留文件吗?

这是我正在尝试的代码

        int originalNumDocs = writer.numDocs();

        for (File f : queue) {
            FileReader fr = null;
            try {
                Document doc = new Document();              
                //===================================================
                // add contents of file
                //===================================================
                fr = new FileReader(f);
                doc.add(new TextField("contents", fr));

                String targetFileStr = IOUtils.toString(new FileInputStream(f), "UTF-8");
                doc.add(new StringField("xmlContent", targetFileStr, Field.Store.YES));

                doc.add(new StringField("path", f.getPath(), Field.Store.YES));
                doc.add(new StringField("filename", f.getName(), Field.Store.YES));

                writer.addDocument(doc);
                System.out.println("Added: " + f);                              
            } catch (Exception e) {
                System.out.println("Could not add: " + f);
                e.printStackTrace();
            } finally {
                fr.close();

                File afile = f;
                if(afile.renameTo(new File("C:/Personal/Logging/OutputDir/" + afile.getName()))){
                    System.out.println("File is moved successful!");
                }else{
                    System.out.println("File is failed to move!");
                }
            }
        }

        int newNumDocs = writer.numDocs();
        System.out.println("");
        System.out.println("************************");
        System.out.println((newNumDocs - originalNumDocs) + " documents added.");
        System.out.println("************************");
        writer.commit();
        queue.clear();

我每 30 秒调用一次此代码。它在Tomcat中运行。

【问题讨论】:

    标签: lucene


    【解决方案1】:

    FileInputStream 可以在该行中:

    String targetFileStr = IOUtils.toString(new FileInputStream(f), "UTF-8");
    

    保持开放?也许尝试将其更改为:

    FileInputStream fileStream = new FileInputStream(f);
    String targetFileStr = IOUtils.toString(fileStream, "UTF-8");
    

    并在您的 finally 块中调用 fileStream.close()

    【讨论】:

      猜你喜欢
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多