java - 从 Zip 文件中的文件中读取内容

标签 java zip extract apache-tika

我正在尝试创建一个简单的 java 程序,该程序从 zip 文件中的文件中读取和提取内容。 Zip 文件包含 3 个文件(txt、pdf、docx)。我需要阅读所有这些文件的内容,为此我使用 Apache Tika

有人可以帮我实现这个功能吗?到目前为止我已经尝试过,但没有成功

代码片段

public class SampleZipExtract {


    public static void main(String[] args) {

        List<String> tempString = new ArrayList<String>();
        StringBuffer sbf = new StringBuffer();

        File file = new File("C:\\Users\\xxx\\Desktop\\abc.zip");
        InputStream input;
        try {

          input = new FileInputStream(file);
          ZipInputStream zip = new ZipInputStream(input);
          ZipEntry entry = zip.getNextEntry();

          BodyContentHandler textHandler = new BodyContentHandler();
          Metadata metadata = new Metadata();

          Parser parser = new AutoDetectParser();

          while (entry!= null){

                if(entry.getName().endsWith(".txt") || 
                           entry.getName().endsWith(".pdf")||
                           entry.getName().endsWith(".docx")){
              System.out.println("entry=" + entry.getName() + " " + entry.getSize());
                     parser.parse(input, textHandler, metadata, new ParseContext());
                     tempString.add(textHandler.toString());
                }
           }
           zip.close();
           input.close();

           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());
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TikaException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

最佳答案

如果您想知道如何从每个 ZipEntry 获取文件内容,这实际上非常简单。这是一个示例代码:

public static void main(String[] args) throws IOException {
    ZipFile zipFile = new ZipFile("C:/test.zip");

    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while(entries.hasMoreElements()){
        ZipEntry entry = entries.nextElement();
        InputStream stream = zipFile.getInputStream(entry);
    }
}

一旦你有了 InputStream,你就可以随心所欲地阅读它。

关于java - 从 Zip 文件中的文件中读取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15667125/

相关文章:

php - extract() 有什么问题?

executable - 自解压可执行文件是如何制作的?

java - mysql/jdbc : Deadlock

java - 通过 Firebase 身份验证的最新更改。谷歌登录?

gradle - 如何使用 Gradle 生成源代码的 ZIP?

xcode - 像 zip 一样组合文件夹和文件

python - 从字符串数据 pandas 中提取关键字

java - 在 JSP/EL 中通过循环连接

java - Swing 绘制网格。奇怪的结果

python - 我们还应该为 ZipFile.open 捕获什么异常