Java Code Examples for java.util.zip.ZipInputStream#closeEntry()

The following examples show how to use java.util.zip.ZipInputStream#closeEntry() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileHelper.java    From PdDroidPublisher with GNU General Public License v3.0 6 votes vote down vote up
private static void unzip(File folder, InputStream inputStream) throws IOException
{
    ZipInputStream zipIs = new ZipInputStream(inputStream); 
    ZipEntry ze = null;

       while ((ze = zipIs.getNextEntry()) != null) {

           FileOutputStream fout = new FileOutputStream(new File(folder, ze.getName()));

           byte[] buffer = new byte[1024];
           int length = 0;

           while ((length = zipIs.read(buffer))>0) {
           fout.write(buffer, 0, length);
           }
           zipIs.closeEntry();
           fout.close();
       }
       zipIs.close();
}
 
Example 2
Source File: Helper.java    From Easer with GNU General Public License v3.0 6 votes vote down vote up
private static boolean is_valid_easer_export_data(Context context, Uri uri) throws IOException {
    final String re_top_level = "^[^/]+$";
    final String re_any_of_valid_dirs = "^(?:(?:event)|(?:script)|(?:profile)|(?:scenario)|(?:condition))(?:/.*)?$";

    InputStream inputStream = context.getContentResolver().openInputStream(uri);
    ZipInputStream zip = new ZipInputStream(inputStream);
    try {
        for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
            String name = entry.getName();
            if (!name.matches(re_any_of_valid_dirs)) {
                return false;
            }
            if (name.matches(re_top_level)) {
                if (!entry.isDirectory())
                    return false;
            }
        }
    } finally {
        zip.closeEntry();
        zip.close();
    }
    return true;
}
 
Example 3
Source File: AddressPool.java    From hasor with Apache License 2.0 6 votes vote down vote up
/**从保存的地址本中恢复数据。*/
public synchronized void restoreConfig(InputStream inStream) throws IOException {
    ZipInputStream zipStream = new ZipInputStream(inStream);
    //
    try {
        synchronized (this.poolLock) {
            ZipEntry zipEntry = null;
            while ((zipEntry = zipStream.getNextEntry()) != null) {
                String serviceID = zipEntry.getName();
                serviceID = FilenameUtils.getBaseName(serviceID);
                AddressBucket bucket = this.addressPool.get(serviceID);
                if (bucket == null) {
                    continue;
                }
                bucket.readFromZip(zipStream);
                zipStream.closeEntry();
            }
        }
    } catch (Exception e) {
        this.logger.error("read the snapshot file error :" + e.getMessage(), e);
    }
}
 
Example 4
Source File: OS.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public static void ZipExplodeToHere(String zippath) throws FileNotFoundException, IOException  {
	byte buffer[] = new byte[10240];
	File zipfile = new File(zippath);
	File outfolder = new File(zipfile.getParentFile().getAbsolutePath());
	outfolder.mkdirs();
	ZipInputStream zis = new ZipInputStream(new FileInputStream(zippath));
	ZipEntry ze = zis.getNextEntry();
	while (ze != null) {
		FileOutputStream fout = new FileOutputStream(outfolder.getAbsolutePath()+File.separator+ze.getName());
		int len;
		while ((len=zis.read(buffer))>0) {
			fout.write(buffer,0,len);
		}
		fout.close();
		ze=zis.getNextEntry();
	}
	zis.closeEntry();
	zis.close();
}
 
Example 5
Source File: ZipArchive.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
public static File unzip(File in, File out) throws FileNotFoundException, IOException {
    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(in));
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(out, fileName);
        if (ze.isDirectory()) {
            newFile.mkdirs();
        } else {
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }
        zis.closeEntry();
        ze = zis.getNextEntry();
    }
    zis.close();
    return out;
}
 
Example 6
Source File: IotPkiManageClient.java    From bce-sdk-java with Apache License 2.0 6 votes vote down vote up
private Map<String, String> unzipCert(byte[] certZip) throws IOException {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(certZip);
    ZipInputStream zipInputStream = new ZipInputStream(byteArrayInputStream);
    Map<String, String> deviceIdCertMap = new HashMap<String, String>();
    ZipEntry entry = zipInputStream.getNextEntry();
    byte[] buffer = new byte[1024];
    while (entry != null) {
        String name = entry.getName();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len;
        while ((len = zipInputStream.read(buffer)) > 0) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        zipInputStream.closeEntry();
        deviceIdCertMap.put(name, new String(byteArrayOutputStream.toByteArray()));
        byteArrayOutputStream.close();

        entry = zipInputStream.getNextEntry();
    }
    zipInputStream.close();
    return deviceIdCertMap;
}
 
Example 7
Source File: ZipInputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_available() throws Exception {

        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "hyts_ZipFile.zip");
        File fl = new File(resources, "hyts_ZipFile.zip");
        FileInputStream fis = new FileInputStream(fl);

        ZipInputStream zis1 = new ZipInputStream(fis);
        ZipEntry entry = zis1.getNextEntry();
        assertNotNull("No entry in the archive.", entry);
        long entrySize = entry.getSize();
        assertTrue("Entry size was < 1", entrySize > 0);
        int i = 0;
        while (zis1.available() > 0) {
            zis1.skip(1);
            i++;
        }
        if (i != entrySize) {
            fail("ZipInputStream.available or ZipInputStream.skip does not " +
                    "working properly. Only skipped " + i +
                    " bytes instead of " + entrySize + " for entry " + entry.getName());
        }
        assertEquals(0, zis1.skip(1));
        assertEquals(0, zis1.available());
        zis1.closeEntry();
        assertEquals(1, zis.available());
        zis1.close();
        try {
            zis1.available();
            fail("IOException expected");
        } catch (IOException ee) {
            // expected
        }
    }
 
Example 8
Source File: RemoteZipHandler.java    From ForgeHax with MIT License 5 votes vote down vote up
public static void extractZip(File zipFile, File destDir) throws IOException {
  byte[] buffer = new byte[1024];
  if (!destDir.exists()) {
    destDir.mkdirs();
  }
  
  ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
  ZipEntry ze = zis.getNextEntry();
  try {
    while (ze != null) {
      String fileName = ze.getName();
      File newFile = new File(destDir, fileName);
      if (ze.isDirectory()) {
        if (newFile.exists()) {
          deleteDirAndContents(newFile);
        }
        newFile.mkdirs();
      } else {
        if (newFile.exists()) {
          newFile.delete();
        }
        if (newFile.getParentFile() != null && !newFile.getParentFile().exists()) {
          newFile.getParentFile().mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(newFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
          fos.write(buffer, 0, len);
        }
        
        fos.close();
      }
      ze = zis.getNextEntry();
    }
  } finally {
    zis.closeEntry();
    zis.close();
  }
}
 
Example 9
Source File: ZipReadRepository.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ZipReadRepository( final InputStream in, final MimeRegistry mimeRegistry ) throws IOException {
  this.mimeRegistry = mimeRegistry;
  root = new ZipReadContentLocation( this, null, "" );

  final ZipInputStream zipIn = new ZipInputStream( in );
  try {
    ZipEntry nextEntry = zipIn.getNextEntry();
    if ( nextEntry == null ) {
      throw new IOException( "This repository is empty or does not point to a ZIP file" );
    }

    while ( nextEntry != null ) {
      final String[] buildName = RepositoryUtilities.splitPath( nextEntry.getName(), "/" );
      if ( nextEntry.isDirectory() ) {
        root.updateDirectoryEntry( buildName, 0, nextEntry );
      } else {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final Deflater def = new Deflater( nextEntry.getMethod() );
        try {
          final DeflaterOutputStream dos = new DeflaterOutputStream( bos, def );
          try {
            IOUtils.getInstance().copyStreams( zipIn, dos );
            dos.flush();
          } finally {
            dos.close();
          }
        } finally {
          def.end();
        }
        root.updateEntry( buildName, 0, nextEntry, bos.toByteArray() );
      }

      zipIn.closeEntry();
      nextEntry = zipIn.getNextEntry();
    }
  } finally {
    zipIn.close();
  }
}
 
Example 10
Source File: Dependencies.java    From eclipse-wakatime with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void unzip(String zipFile, File outputDir) throws IOException {
    if(!outputDir.exists())
        outputDir.mkdirs();

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(outputDir, fileName);

        if (ze.isDirectory()) {
            newFile.mkdirs();
        } else {
            FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }

        ze = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();
}
 
Example 11
Source File: ZipInputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testAvailable() throws Exception {
    // NOTE: We don't care about the contents of any of these entries as long as they're
    // not empty.
    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(
            zip(new String[] { "foo", "bar", "baz" }, new byte[] { 0, 0, 0, 1, 1, 1 })));

    assertEquals(1, zis.available());
    zis.getNextEntry();
    assertEquals(1, zis.available());
    zis.closeEntry();
    // On Android M and below, this call would return "1". That seems a bit odd given that the
    // contract for available states that we should return 1 if there are any bytes left to read
    // from the "current" entry.
    assertEquals(0, zis.available());

    // There shouldn't be any bytes left to read if the entry is fully consumed...
    zis.getNextEntry();
    Streams.readFullyNoClose(zis);
    assertEquals(0, zis.available());

    // ... or if the entry is fully skipped over.
    zis.getNextEntry();
    zis.skip(Long.MAX_VALUE);
    assertEquals(0, zis.available());

    // There are no entries left in the file, so there whould be nothing left to read.
    assertNull(zis.getNextEntry());
    assertEquals(0, zis.available());

    zis.close();
}
 
Example 12
Source File: FileUtil.java    From NutzCodeInsight with Apache License 2.0 5 votes vote down vote up
/**
 * 解压文件
 *
 * @param file
 * @param root
 */
public static void extractZipFile(File file, File root) {
    byte[] buffer = new byte[BUFFER];
    try {
        ZipInputStream zis = new ZipInputStream(new FileInputStream(file), Charset.forName("GBK"));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            String fileName = entry.getName();
            if (!fileName.contains("__MACOSX")) {
                File newFile = new File(root.getAbsolutePath() + File.separator + fileName);
                if (entry.isDirectory()) {
                    newFile.mkdirs();
                } else {
                    newFile.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(newFile);
                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                }
            }
        }
        zis.closeEntry();
        zis.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example 13
Source File: FileUtils.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void unzip(InputStream is, String dir) throws IOException {
    File dest = new File(dir);
    if (!dest.exists()) {
        dest.mkdirs();
    }

    if (!dest.isDirectory())
        throw new IOException("Invalid Unzip destination " + dest);
    if (null == is) {
        throw new IOException("InputStream is null");
    }

    ZipInputStream zip = new ZipInputStream(is);

    ZipEntry ze;
    while ((ze = zip.getNextEntry()) != null) {
        final String path = dest.getAbsolutePath()
                + File.separator + ze.getName();

        String zeName = ze.getName();
        char cTail = zeName.charAt(zeName.length() - 1);
        if (cTail == File.separatorChar) {
            File file = new File(path);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    throw new IOException("Unable to create folder " + file);
                }
            }
            continue;
        }

        FileOutputStream fout = new FileOutputStream(path);
        byte[] bytes = new byte[1024];
        int c;
        while ((c = zip.read(bytes)) != -1) {
            fout.write(bytes, 0, c);
        }
        zip.closeEntry();
        fout.close();
    }
}
 
Example 14
Source File: FileUtils.java    From ChatKeyboard-master with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void unzip(InputStream is, String dir) throws IOException {
    File dest = new File(dir);
    if (!dest.exists()) {
        dest.mkdirs();
    }

    if (!dest.isDirectory())
        throw new IOException("Invalid Unzip destination " + dest);
    if (null == is) {
        throw new IOException("InputStream is null");
    }

    ZipInputStream zip = new ZipInputStream(is);

    ZipEntry ze;
    while ((ze = zip.getNextEntry()) != null) {
        final String path = dest.getAbsolutePath()
                + File.separator + ze.getName();

        String zeName = ze.getName();
        char cTail = zeName.charAt(zeName.length() - 1);
        if (cTail == File.separatorChar) {
            File file = new File(path);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    throw new IOException("Unable to create folder " + file);
                }
            }
            continue;
        }

        FileOutputStream fout = new FileOutputStream(path);
        byte[] bytes = new byte[1024];
        int c;
        while ((c = zip.read(bytes)) != -1) {
            fout.write(bytes, 0, c);
        }
        zip.closeEntry();
        fout.close();
    }
}
 
Example 15
Source File: LocalFileSystemProvider.java    From judgels with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void uploadZippedFiles(List<String> destinationDirectoryPath, File zippedFiles, boolean includeDirectory) throws IOException {
    File destinationDirectory = FileUtils.getFile(baseDir, toArray(destinationDirectoryPath));
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zippedFiles));
    byte[] buffer = new byte[4096];
    int entries = 0;
    long total = 0;
    ZipEntry ze = zis.getNextEntry();
    try {
        while (ze != null) {
            String filename = ze.getName();
            File file = new File(destinationDirectory, filename);
            if ((includeDirectory) && (ze.isDirectory())) {
                file.mkdirs();
            } else {
                if (((includeDirectory) && (file.getCanonicalPath().startsWith(destinationDirectory.getCanonicalPath()))) || (destinationDirectory.getAbsolutePath().equals(file.getParentFile().getAbsolutePath()))) {
                    FileOutputStream fos = new FileOutputStream(file);
                    try {
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                            total += len;
                        }
                        entries++;
                    } finally {
                        fos.close();
                    }
                }
            }

            zis.closeEntry();
            if (entries > TOOMANY) {
                throw new IllegalStateException("Too many files to unzip.");
            }
            if (total > TOOBIG) {
                throw new IllegalStateException("File too big to unzip.");
            }

            ze = zis.getNextEntry();
        }
    } finally {
        zis.close();
    }
}
 
Example 16
Source File: ExtensionPackage.java    From GreasySpoon with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Extract compressed directory to given path 
 * @param zipentry the compressed directory to extract
 * @param zipFile the file containing the compressed directory
 * @param extractionpath the path where to extract the directory
 * @return List of extracted directories and file
 * @throws Exception
 */
private StringBuilder extractDir(ZipEntry zipentry, String zipFile,String extractionpath) throws Exception {
	byte[] buf = new byte[8128];
	int n;
	String entryName;
	String rootPath = zipentry.getName();

	//Cleanup name by using generic path separator and
	rootPath = rootPath.replace('\\', '/');
	File newFile = new File(extractionpath+rootPath);
	newFile.mkdirs();
	if (debug)System.out.println("creating repository:"+newFile);
	//lets inspect the zip file
	ZipInputStream zipinputstream = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
	BufferedOutputStream bos;
	StringBuilder directoriesList = new StringBuilder();
	StringBuilder fileList = new StringBuilder();
	while ( (zipentry = zipinputstream.getNextEntry()) != null) {
		
		//for each entry to be extracted
		entryName = zipentry.getName();
		//Cleanup name by using generic path separator and
		entryName = entryName.replace('\\', '/');
		if (debug)System.out.println("extracting:"+entryName);
		//check that entry match library path
		if (!entryName.startsWith(rootPath) || entryName.contains("..")) {
			if (debug) System.out.println("SKIP: entryname: ["+entryName+ "] ==> [" + rootPath +"]");
			zipinputstream.closeEntry();
			continue;
		}
		newFile = new File(entryName);
		if (newFile.exists()){
			zipinputstream.closeEntry();
			message.append(entryName).append("\n");
			continue;
		}
		
		//if entry is a path, just create it
		if (entryName.endsWith("/")){
			if (debug)System.out.println("Entry is a path - creating it: "+entryName);
			File destfile =  new File(extractionpath+entryName);
			destfile.mkdirs();
			directoriesList.append(extractionpath).append(entryName).append("\n");
			continue;
		} else {
			//extract file content
			bos = new BufferedOutputStream(new FileOutputStream(extractionpath+entryName));
			while ((n = zipinputstream.read(buf)) > -1){
				bos.write(buf, 0, n);
			}
			if (debug)System.out.println("Entry is a file - extracting it to "+extractionpath+entryName);
			bos.close();
			fileList.append(extractionpath).append(entryName).append("\n");
		}
		//close entry
		zipinputstream.closeEntry();
	}//while
	zipinputstream.close();
	return fileList.append(directoriesList);
}
 
Example 17
Source File: Zip.java    From core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Unzips the specified file into the specified directory
 * 
 * @param zipFileName
 *            Name of the file to be unzipped
 * @param subDirectory
 *            If not null then will put the resulting unzipped files into
 *            the subdirectory. If null then resulting files end up in same
 *            directory as the zip file.
 * @return If successful, directory name where files extracted to. If
 *         problem then null.
 */
public static String unzip(String zipFileName, String subDirectory) {
	IntervalTimer timer = new IntervalTimer();
	
	try {
		// Determine directory where to put the unzipped files
		String parentDirName = new File(zipFileName).getParent();
		String directoryName = parentDirName;
		if (subDirectory != null) {
			directoryName += "/" + subDirectory;
		}
		
		logger.info("Unzipping file {} into directory {}", 
				zipFileName, directoryName);
		
		// Extract the files
		ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
		ZipEntry ze = zis.getNextEntry();
		while (ze != null) {
			String entryName = ze.getName();
			logger.info("Extracting file {}", entryName);
			File f = new File(directoryName + "/" + entryName);
			
			// Make sure necessary directory exists
			f.getParentFile().mkdirs();
			
			FileOutputStream fos = new FileOutputStream(f);
			int len;
			byte buffer[] = new byte[BUFFER_SIZE];
			while ((len = zis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);				
			}
			fos.close();
			
			ze = zis.getNextEntry();			
		}
		
		// Clean things up
		zis.closeEntry();
		zis.close();
		
		logger.info("Successfully extracted files from {} into directory {}. Took {} msec.", 
				zipFileName, directoryName, timer.elapsedMsec());
		return directoryName;
	} catch (Exception e) {
		// Log problem
		logger.error("Error occurred when processing file {}", zipFileName, e);
		return null;
	}
}
 
Example 18
Source File: UploadConfig.java    From iaf with Apache License 2.0 4 votes vote down vote up
private String processZipFile(IPipeLineSession session)
		throws PipeRunException, IOException {
	StringBuilder result = new StringBuilder();
	Object formFile = session.get("file");
	if (formFile instanceof InputStream) {
		InputStream inputStream = (InputStream) formFile;
		try {
			if (inputStream.available() > 0) {
				ZipInputStream archive = new ZipInputStream(inputStream);
				int counter = 1;
				for (ZipEntry entry = archive
						.getNextEntry(); entry != null; entry = archive
								.getNextEntry()) {
					String entryName = entry.getName();
					int size = (int) entry.getSize();
					if (size > 0) {
						byte[] b = new byte[size];
						int rb = 0;
						while ((size - rb) > 0) {
							int chunk = archive.read(b, rb, size - rb);
							if (chunk == -1) {
								break;
							}
							rb += chunk;
						}
						ByteArrayInputStream bais = new ByteArrayInputStream(b,
								0, rb);
						String fileNameSessionKey = "file_zipentry" + counter;
						session.put(fileNameSessionKey, bais);
						if (result.length()!=0){
							result.append("\n" + new String(new char[32]).replace("\0", "-") + "\n"); //Creates separator between config results
						}
						result.append(processJarFile(session,
								entryName, fileNameSessionKey));
						session.remove(fileNameSessionKey);
					}
					archive.closeEntry();
					counter++;
				}
				archive.close();
			} else {
				throw new PipeRunException(this, getLogPrefix(session)
						+ "Cannot read zip file");
			}
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}
	return result.toString();
}
 
Example 19
Source File: FlatStorageImporterExporterEx.java    From cms with Apache License 2.0 4 votes vote down vote up
public void importFromZipStep2(InputStream is) throws WPBIOException
{
 log.log(Level.INFO, "Begin import from zip step 2");
    ZipInputStream zis = new ZipInputStream(is);
    // we need to stop the notifications during import
    dataStorage.stopNotifications();
    try
    {
        ZipEntry ze = null;
        while ((ze = zis.getNextEntry()) != null)
        {
            String name = ze.getName();
            if (name.indexOf(PATH_SITE_PAGES)>=0)
            {
                if (name.indexOf("pageSource.txt")>=0)
                {
                    importWebPageSource(zis, ze.getName());
                }
            } else
            if (name.indexOf(PATH_SITE_PAGES_MODULES) >= 0)
            {
                if (name.indexOf("moduleSource.txt")>=0)
                {
                    importWebPageModuleSource(zis, ze.getName());
                }
            } else              
            if (name.indexOf(PATH_ARTICLES) >= 0)
            {
                if (name.indexOf("articleSource.txt")>=0)
                {
                    importArticleSource(zis, ze.getName());
                }
            } else
            if (name.indexOf(PATH_FILES) >= 0)
            {
                if (name.indexOf("/content/")>=0 && !name.endsWith("/"))
                {
                    importFileContent(zis, ze.getName());
                }
            }
            zis.closeEntry();
        }
    } catch (Exception e)
    {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("cannot import from  zip step 2", e);
    }
    finally
    {
        log.log(Level.INFO, "End import from zip step 2");
    }
}
 
Example 20
Source File: UnZiper.java    From nopol with GNU General Public License v2.0 4 votes vote down vote up
public static void unZipIt(byte[] zipFile, String outputFolder) {
	byte[] buffer = new byte[1024];

	try {

		//create output directory is not exists
		File folder = new File(outputFolder);
		if (!folder.exists()) {
			folder.mkdir();
		}

		//get the zip file content
		ZipInputStream zis =
				new ZipInputStream(new ByteArrayInputStream(zipFile));
		//get the zipped file list entry
		ZipEntry ze = zis.getNextEntry();

		while (ze != null) {
			String fileName = ze.getName();
			File newFile = new File(outputFolder + File.separator + fileName);

			//create all non exists folders
			//else you will hit FileNotFoundException for compressed folder
			new File(newFile.getParent()).mkdirs();

			FileOutputStream fos = new FileOutputStream(newFile);

			int len;
			while ((len = zis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}

			fos.close();
			ze = zis.getNextEntry();
		}

		zis.closeEntry();
		zis.close();
	} catch (IOException ex) {
		ex.printStackTrace();
	}
}