Search code examples
javawindowszipunzip

How to Unzip all the Zip folder in an directory in Java?


I want to write an Program where it will fetch all the Zip files present in an folder and unzip into an destination folder. I was able to write an program where i can unzip one single zip file but i want to unzip all the zip files present in that folder how can i do it?


Solution

  • Its not pretty but you get the idea.

    1. Using the NIO Files api from Java 7 stream the directory filtering the out the zip files
    2. Use the ZIP api to access each ZipEntry in the archive
    3. Using the NIO api write the files to the specified directory

      public class Unzipper {
      
        public static void main(String [] args){
          Unzipper unzipper = new Unzipper();
          unzipper.unzipZipsInDirTo(Paths.get("D:/"), Paths.get("D:/unzipped"));
        }
      
        public void unzipZipsInDirTo(Path searchDir, Path unzipTo ){
      
          final PathMatcher matcher = searchDir.getFileSystem().getPathMatcher("glob:**/*.zip");
          try (final Stream<Path> stream = Files.list(searchDir)) {
              stream.filter(matcher::matches)
                      .forEach(zipFile -> unzip(zipFile,unzipTo));
          }catch (IOException e){
              //handle your exception
          }
        }
      
       public void unzip(Path zipFile, Path outputPath){
          try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile))) {
      
              ZipEntry entry = zis.getNextEntry();
      
              while (entry != null) {
      
                  Path newFilePath = outputPath.resolve(entry.getName());
                  if (entry.isDirectory()) {
                      Files.createDirectories(newFilePath);
                  } else {
                      if(!Files.exists(newFilePath.getParent())) {
                          Files.createDirectories(newFilePath.getParent());
                      }
                      try (OutputStream bos = Files.newOutputStream(outputPath.resolve(newFilePath))) {
                          byte[] buffer = new byte[Math.toIntExact(entry.getSize())];
      
                          int location;
      
                          while ((location = zis.read(buffer)) != -1) {
                              bos.write(buffer, 0, location);
                          }
                      }
                  }
                  entry = zis.getNextEntry();
              }
          }catch(IOException e){
              throw new RuntimeException(e);
              //handle your exception
          }
        }
      }