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

新手上路,请多包涵

我正在尝试创建一个简单的 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();
        }
    }
}

原文由 S Jagdeesh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

如果您想知道如何从每个 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 后,您可以随心所欲地阅读它。

原文由 Rodrigo Sasaki 发布,翻译遵循 CC BY-SA 3.0 许可协议

从 Java 7 开始, NIO АР I 提供了一种更好、更通用的方式来访问 ZIP 或 JAR 文件的内容。实际上,它现在是一个统一的 API,允许您像对待普通文件一样对待 ZIP 文件。

要在此 API 中提取 ZIP 文件中包含的所有文件,您需要执行以下操作。

在Java 8中

private void extractAll(URI fromZip, Path toDirectory) throws IOException {
    FileSystems.newFileSystem(fromZip, Collections.emptyMap())
            .getRootDirectories()
            .forEach(root -> {
                // in a full implementation, you'd have to
                // handle directories
                Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
            });
}

在 Java 7 中

private void extractAll(URI fromZip, Path toDirectory) throws IOException {
    FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());

    for (Path root : zipFs.getRootDirectories()) {
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                // You can do anything you want with the path here
                Files.copy(file, toDirectory);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException {
                // In a full implementation, you'd need to create each
                // sub-directory of the destination directory before
                // copying files into it
                return super.preVisitDirectory(dir, attrs);
            }
        });
    }
}

原文由 LordOfThePigs 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题