java

ybzsozfc  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(521)

我有一个受密码保护的zip文件[以base64编码数据和zip文件名的形式],其中包含一个xml。我希望在不将任何内容写入磁盘的情况下解析xml。在zip4j中如何实现这一点?下面是我试过的。

  1. String docTitle = request.getDocTitle();
  2. byte[] decodedFileData = Base64.getDecoder().decode(request.getBase64Data());
  3. InputStream inputStream = new ByteArrayInputStream(decodedFileData);
  4. try (ZipInputStream zipInputStream = new ZipInputStream(inputStream, password)) {
  5. while ((localFileHeader = zipInputStream.getNextEntry()) != null) {
  6. String fileTitle = localFileHeader.getFileName();
  7. File extractedFile = new File(fileTitle);
  8. try (InputStream individualFileInputStream = org.apache.commons.io.FileUtils.openInputStream(extractedFile)) {
  9. // Call parser
  10. parser.parse(localFileHeader.getFileName(),
  11. individualFileInputStream));
  12. } catch (IOException e) {
  13. // Handle IOException
  14. }
  15. }
  16. } catch (IOException e) {
  17. // Handle IOException
  18. }

把我甩了 java.io.FileNotFoundException: File 'xyz.xml' does not exist at线 FileUtils.openInputStream(extractedFile) . 你能告诉我做这件事的正确方法吗?

cyej8jka

cyej8jka1#

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

  1. byte[] decodedFileData = Base64.getDecoder().decode(request.getBase64Data());
  2. InputStream inputStream = new ByteArrayInputStream(decodedFileData);
  3. try (ZipInputStream zipInputStream = new ZipInputStream(inputStream, password)) {
  4. ZipEntry zipEntry = null;
  5. while ((zipEntry = zipInputStream.getNextEntry()) != null) {
  6. byte[] fileContent = IOUtils.toByteArray(zipInputStream);
  7. parser.parse(zipEntry.getName(),
  8. new ByteArrayInputStream(fileContent)));
  9. }
  10. } catch (Exception e) {
  11. // Handle Exception
  12. }

相关问题