How to read file from ZIP using InputStream?

后端 未结 7 850
旧巷少年郎
旧巷少年郎 2020-11-29 09:11

I must get file content from ZIP archive (only one file, I know its name) using SFTP. The only thing I\'m having is ZIP\'s InputStream. Most examples show how g

7条回答
  •  死守一世寂寞
    2020-11-29 09:28

    Unzip archive (zip) with preserving file structure into given directory. Note; this code use deps on "org.apache.commons.io.IOUtils"), but you can replace it by yours custom 'read-stream' code

    public static void unzipDirectory(File archiveFile, File destinationDir) throws IOException
    {
      Path destPath = destinationDir.toPath();
      try (ZipInputStream zis = new ZipInputStream(new FileInputStream(archiveFile)))
      {
        ZipEntry zipEntry;
        while ((zipEntry = zis.getNextEntry()) != null)
        {
          Path resolvedPath = destPath.resolve(zipEntry.getName()).normalize();
          if (!resolvedPath.startsWith(destPath))
          {
            throw new IOException("The requested zip-entry '" + zipEntry.getName() + "' does not belong to the requested destination");
          }
          if (zipEntry.isDirectory())
          {
            Files.createDirectories(resolvedPath);
          } else
          {
            if(!Files.isDirectory(resolvedPath.getParent()))
            {
              Files.createDirectories(resolvedPath.getParent());
            }
            try (FileOutputStream outStream = new FileOutputStream(resolvedPath.toFile()))
            {
              IOUtils.copy(zis, outStream);
            }
          }
        }
      }
    }
    

提交回复
热议问题