1

我有一个受密码保护的 zip 文件 [以 base64 编码数据和 zip 文件名称的形式],其中包含一个 xml。我希望在不向磁盘写入任何内容的情况下解析该 xml。在 Zip4j 中执行此操作的方法是什么?以下是我尝试过的。

        String docTitle = request.getDocTitle();
        byte[] decodedFileData = Base64.getDecoder().decode(request.getBase64Data());

        InputStream inputStream = new ByteArrayInputStream(decodedFileData);
        try (ZipInputStream zipInputStream = new ZipInputStream(inputStream, password)) {

            while ((localFileHeader = zipInputStream.getNextEntry()) != null) {
                String fileTitle = localFileHeader.getFileName();
                File extractedFile = new File(fileTitle);
                try (InputStream individualFileInputStream =  org.apache.commons.io.FileUtils.openInputStream(extractedFile)) {
                    // Call parser
                    parser.parse(localFileHeader.getFileName(),
                            individualFileInputStream));
                } catch (IOException e) {
                    // Handle IOException
                }
            }
        } catch (IOException e) {
            // Handle IOException
        }

这让我java.io.FileNotFoundException: File 'xyz.xml' does not exist大吃一惊FileUtils.openInputStream(extractedFile)。你能建议我这样做的正确方法吗?

4

1 回答 1

3

ZipInputStream保留 zip 文件的所有内容。每次调用都会zipInputStream.getNextEntry()传递每个文件的内容并将“指针”移动到下一个条目(文件)。您还可以在移至下一个条目之前读取文件 ( ZipInputStream.read )。

你的情况:

        byte[] decodedFileData = Base64.getDecoder().decode(request.getBase64Data());
        InputStream inputStream = new ByteArrayInputStream(decodedFileData);
        try (ZipInputStream zipInputStream = new ZipInputStream(inputStream, password)) {
            ZipEntry zipEntry = null;
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                byte[] fileContent = IOUtils.toByteArray(zipInputStream);
                parser.parse(zipEntry.getName(),
                            new ByteArrayInputStream(fileContent)));      
            }
        } catch (Exception e) {
            // Handle Exception
        }
于 2021-01-06T19:44:19.003 回答