Java - 迭代许多文件和文件夹

时间:2012-04-18 08:26:10

标签: java file-io iteration

我想迭代放在深层文件夹层次结构中的很多文件。 有问题的文件是我打算用POI处理的15 GB MS Word文档。 POI工作正常,但是一个简单的递归函数会创建一个OutOfMemoryException:

public void checkDir(File dir) {
    for (File child : dir.listFiles()) {
        if (".".equals(child.getName()) || "..".equals(child.getName()))
            continue; // Ignore the self and parent aliases.
        if (child.isFile())
            processFile(child); // do something
        else if (child.isDirectory())
            checkDir(child);
    }
}

// check if the word file can be read by POI
private void processFile(File file) {
InputStream in = null;
try {
    in = new FileInputStream(file);
    WordExtractor extractor = null;

    try {
        extractor = new WordExtractor(in);
        extractor.getText();
    } catch (Exception e) {
        // This can happen if the file has the "doc" extension, but is
        // not a Word document
        throw new Exception(file + "is not a doc");
    } finally {
        in.close();
        in = null;
    }
} catch (Exception e) {
    // log the error to a file
    FileWriter fw = null;
    try {
        fw = new FileWriter("corruptFiles.txt", true);
        fw.write(file.getAbsolutePath() + "\r\n");
    } catch (Exception e2) {
        e.printStackTrace();
    } finally {
        try {
            fw.close();
        } catch (IOException e3) {
        }
    }       
}

尝试使用org.apache.commons.io.FileUtils.iterateFiles完成此操作会产生相同的异常:

String[] extensions = { "doc" };

Iterator<File> iter = FileUtils.iterateFiles(dir, extensions, true);
for(; iter.hasNext();)
{
    File file = iter.next();
    processFile(file); // do something
}

我在Windows 7上运行Java 6,不允许移动或重新排列文件。

我有什么选择?

感谢您的时间。

[编辑]添加了processFile函数。在将堆大小增加到512 MB之后,刚刚使用简化版本的processFile成功运行。 总之,我的问题在某种程度上与POI相关,而不是迭代文件。

private void processFile(File file) {
    System.out.println(file);
}

[EDIT2]我可以将异常原因缩小到33 MB文件。尝试解析导致java.lang.OutOfMemoryError:Java堆空间异常的结果。我将把票发给POI bug跟踪器。谢谢大家的建议。 我会接受MathAsmLang的答案,因为这有助于克服迭代问题。 我会接受krishnakumarp的评论作为答案,因为他是第一个指出这一点的人,但事实证明这是不可能的; - )

1 个答案:

答案 0 :(得分:0)

因为它是outofmemoryerror,你应该试着用jvm启动 不同的内存参数,即堆大小。