使用 Apache Tika 1.7,如何递归解析 zip 存档中的文件直至达到某个递归限制?
递归部分很重要,因为一个 zip 存档可能包含另一个 zip 存档。
我认为可以使用新的 RecursiveParserWrapper
来完成,但我在网上找不到任何示例 - Jukka 的示例 here使用与 Tika 1.7 提供的接口(interface)不同的接口(interface)
最佳答案
理论上,这应该只是将您指向 Apache Tika Examples page 的情况。 ,但现在递归是 only one still to finish对于该页面。因此,我必须为您获取一个合适的单元测试,并对其进行修改以达到限制
基本上,您需要的关键类是 EmbeddedDocumentExtractor 。您需要在 ParseContext
上提供该实现,并将其用于递归。通常你可以使用 ParsingEmbeddedDocumentExtractor ,但既然你想要限制,你需要一个自定义的
尝试如下:
protected class RecurseWithLimits extends ParsingEmbeddedDocumentExtractor {
protected static final int MAX_DEPTH = 4;
private int depth;
private ParseContext context;
private RecurseWithLimits child;
protected RecurseWithLimits() {
this(0, new ParseContext());
}
private RecurseWithLimits(int depth, ParseContext context) {
super(context);
this.context = context;
this.depth = depth;
}
@Override
public void parseEmbedded(
InputStream stream, ContentHandler handler, Metadata metadata, boolean outputHtml)
throws SAXException, IOException {
if (child == null) {
if (depth >= MAX_DEPTH) {
// Too deep, skip
return;
}
child = new RecurseWithLimits(depth+1);
context.set(EmbeddedDocumentExtractor,child);
}
super.parse(stream,handler,metadata,outputHtml);
}
}
// In main parsing code
Parser parser = new AutoDetectParser();
InputStream inp = TikaInputStream.get(new File("test.zip"));
ContentHandler text = new BodyContentHandler();
ParseContext context = new ParseContext();
context.set(EmbeddedDocumentExtractor, new RecurseWithLimits());
parser.parse(inp, new Metadata(), text, context);
关于java - Apache 蒂卡 1.7 : Parse files in a zip archive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28102943/