使用Apache Tika从归档中提取文件的名称

时间:2012-09-27 11:08:50

标签: java apache parsing apache-tika

如果输入文件不是存档,我希望Tika只输出存档中文件的名称(如果输入文件是存档)和文件内容。我怎么能这样做?

1 个答案:

答案 0 :(得分:4)

我扩展了ParsingEmbeddedDocumentExtractor类

class CustomParsingEmbeddedDocumentExtractor extends ParsingEmbeddedDocumentExtractor {
  public CustomParsingEmbeddedDocumentExtractor(ParseContext context) {
    super(context);
  }

  public void parseEmbedded(
        InputStream stream, ContentHandler handler, Metadata metadata, boolean outputHtml)
        throws SAXException, IOException {


    String name = metadata.get(Metadata.RESOURCE_NAME_KEY);
    if (name != null && name.length() > 0 ) {
        handler.startElement(XHTML, "h1", "h1", new AttributesImpl());
        char[] chars = name.toCharArray();
        handler.characters(chars, 0, chars.length);
        handler.endElement(XHTML, "h1", "h1");
    }

    //Removed the parsing logic here.. We just want the file names..

  }
}

并在执行someparser.parse()

之前将其设置为ParseContext变量
context.set(EmbeddedDocumentExtractor.class, new CustomParsingEmbeddedDocumentExtractor(this.context));

这仅适用于zip,tar和jar。这对我来说已经足够了。