Home >Java >javaTutorial >How to extract content from files within a ZIP archive using Apache Tika?
Extracting Content from Files Within a Zip Using Apache Tika
To fulfill your requirement of reading and extracting content from files within a zip archive using Apache Tika, you'll need to make some adjustments to your current code. While your approach is largely correct, the issue lies in obtaining the InputStream for each file in the zip.
Here's an updated version of your code that addresses this:
<code class="java">import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.BodyContentHandler; import org.apache.tika.parser.ParseContext; import org.xml.sax.SAXException; public class SampleZipExtractNew { public static void main(String[] args) throws IOException { List<String> tempString = new ArrayList<>(); StringBuffer sbf = new StringBuffer(); File file = new File("C:\Users\xxx\Desktop\abc.zip"); ZipFile zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); BodyContentHandler textHandler = new BodyContentHandler(); Metadata metadata = new Metadata(); Parser parser = new AutoDetectParser(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); try (InputStream inputStream = zipFile.getInputStream(entry)) { if (entry.getName().endsWith(".txt") || entry.getName().endsWith(".pdf") || entry.getName().endsWith(".docx")) { parser.parse(inputStream, textHandler, metadata, new ParseContext()); tempString.add(textHandler.toString()); } } } for (String text : tempString) { System.out.println("Apache Tika - Converted input string : " + text); sbf.append(text); System.out.println("Final text from all the three files " + sbf.toString()); } } }</code>
In this revised code:
The above is the detailed content of How to extract content from files within a ZIP archive using Apache Tika?. For more information, please follow other related articles on the PHP Chinese website!