View Javadoc
1   package au.gov.amsa.gt;
2   
3   import java.io.File;
4   import java.io.FileOutputStream;
5   import java.io.IOException;
6   import java.io.InputStream;
7   import java.util.zip.ZipEntry;
8   import java.util.zip.ZipInputStream;
9   
10  public class ZipUtil {
11  
12      public static void unzip(InputStream is, File folder) {
13          byte[] buffer = new byte[1024];
14          try {
15              // create output directory is not exists
16              if (!folder.exists()) {
17                  folder.mkdir();
18              }
19  
20              // get the zip file content
21              try (ZipInputStream zis = new ZipInputStream(is)) {
22                  // get the zipped file list entry
23                  ZipEntry entry = zis.getNextEntry();
24  
25                  while (entry != null) {
26  
27                      String fileName = entry.getName();
28                      File newFile = new File(folder, fileName);
29                      // create all non existent folders
30                      // else you will hit FileNotFoundException for compressed
31                      // folder
32                      new File(newFile.getParent()).mkdirs();
33  
34                      try (FileOutputStream fos = new FileOutputStream(newFile)) {
35                          int len;
36                          while ((len = zis.read(buffer)) > 0) {
37                              fos.write(buffer, 0, len);
38                          }
39                      }
40                      entry = zis.getNextEntry();
41                  }
42                  zis.closeEntry();
43              }
44          } catch (IOException e) {
45              throw new RuntimeException(e);
46          }
47      }
48  
49  }