挑戰:
您渴望寫一個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中文網其他相關文章!