View Javadoc
1   /*
2    * Copyright (c) 2003 by Atlassian Software Systems Pty. Ltd.
3    * All rights reserved.
4    */
5   package com.atlassian.plugin.util.zip;
6   
7   import org.apache.commons.lang3.StringUtils;
8   import org.slf4j.Logger;
9   import org.slf4j.LoggerFactory;
10  
11  import java.io.BufferedInputStream;
12  import java.io.File;
13  import java.io.FileInputStream;
14  import java.io.FileNotFoundException;
15  import java.io.IOException;
16  import java.util.zip.ZipEntry;
17  
18  public class FileUnzipper extends AbstractUnzipper {
19      private static final Logger log = LoggerFactory.getLogger(FileUnzipper.class);
20  
21      private File zipFile;
22      private File destDir;
23  
24      public FileUnzipper(File zipFile, File destDir) {
25          this.zipFile = zipFile;
26          this.destDir = destDir;
27      }
28  
29      /**
30       * Unzips all files in the archive
31       *
32       * @throws IOException
33       */
34      public void unzip() throws IOException {
35          if ((zipFile == null) || !zipFile.isFile())
36              return;
37  
38          getStreamUnzipper().unzip();
39      }
40  
41      public ZipEntry[] entries() throws IOException {
42          return getStreamUnzipper().entries();
43      }
44  
45      /**
46       * Specify a specific file inside the archive to extract
47       *
48       * @param fileName
49       */
50      public File unzipFileInArchive(String fileName) throws IOException {
51          if ((zipFile == null) || !zipFile.isFile() || StringUtils.isEmpty(fileName)) {
52              return null;
53          }
54  
55          File result = getStreamUnzipper().unzipFileInArchive(fileName);
56          if (result == null) {
57              log.error("The file: {} could not be found in the archive: {}", fileName, zipFile.getAbsolutePath());
58          }
59  
60          return result;
61      }
62  
63      private StreamUnzipper getStreamUnzipper() throws FileNotFoundException {
64          return new StreamUnzipper(new BufferedInputStream(new FileInputStream(zipFile)), destDir);
65      }
66  
67  }