挑战:
您渴望编写一个 Java 程序,使用 Apache Tika 提取并读取 zip 存档中多个文件的内容。具体来说,您的 zip 文件包含文本、PDF 和 docx 文件的混合。
解决方案:
public class ZipContentExtractor { public static void main(String[] args) throws IOException, SAXException, TikaException { File zipFile = new File("C:\Users\xxx\Desktop\abc.zip"); try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile))) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { // Checking file types if (entry.getName().endsWith(".txt") || entry.getName().endsWith(".pdf") || entry.getName().endsWith(".docx")) { // Handling text files if (entry.getName().endsWith(".txt")) { BodyContentHandler textHandler = new BodyContentHandler(); Parser parser = new AutoDetectParser(); parser.parse(zipInputStream, textHandler, new Metadata(), new ParseContext()); System.out.println("TXT file content: " + textHandler.toString()); } // Handling PDF files else if (entry.getName().endsWith(".pdf")) { Metadata metadata = new Metadata(); Parser parser = new PDFParser(); parser.parse(zipInputStream, new StreamingContentHandler(), metadata, new ParseContext()); System.out.println("PDF file content: " + metadata.get("xmpDM:documentID")); } // Handling DOCX files else { BodyContentHandler textHandler = new BodyContentHandler(); Parser parser = new OOXMLParser(); parser.parse(zipInputStream, textHandler, new Metadata(), new ParseContext()); System.out.println("DOCX file content: " + textHandler.toString()); } } } } } }
说明:
以上是如何使用 Apache Tika 读取 Zip 存档中多种文件类型的内容?的详细内容。更多信息请关注PHP中文网其他相关文章!