List of usage examples for java.util.zip ZipEntry isDirectory
public boolean isDirectory()
From source file:com.amazonaws.eclipse.dynamodb.testtool.TestToolManager.java
/** * Unzip the given file into the given directory. * * @param zipFile The zip file to unzip. * @param unzipped The directory to put the unzipped files into. * @throws IOException on file system error. *///from w w w. j a v a 2 s.c o m private void unzip(final File zipFile, final File unzipped) throws IOException { ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile)); try { ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { Path path = new Path(entry.getName()); File dest = new File(unzipped, path.toOSString()); if (entry.isDirectory()) { if (!dest.mkdirs()) { throw new RuntimeException("Failed to create directory while unzipping"); } } else { FileOutputStream output = new FileOutputStream(dest); try { IOUtils.copy(zip, output); } finally { output.close(); } } } } finally { zip.close(); } }
From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java
private void updateWithMetaInf(ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly) throws IOException { ZipFile zin = new ZipFile(jarFile); for (Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements();) { ZipEntry ze = en.nextElement(); if (ze.isDirectory()) { continue; }/* ww w . j a v a2s.co m*/ String zn = ze.getName(); if (metaInfOnly) { if (!zn.startsWith("META-INF/")) { continue; } if (this.extractDuplicates && !entries.add(zn)) { continue; } if (!this.apkMetaInf.isIncluded(zn)) { continue; } } final ZipEntry ne; if (ze.getMethod() == ZipEntry.STORED) { ne = new ZipEntry(ze); } else { ne = new ZipEntry(zn); } zos.putNextEntry(ne); InputStream is = zin.getInputStream(ze); copyStreamWithoutClosing(is, zos); is.close(); zos.closeEntry(); } zin.close(); }
From source file:bammerbom.ultimatecore.bukkit.UltimateUpdater.java
/** * Part of Zip-File-Extractor, modified by Gravity for use with Updater. * * @param file the location of the file to extract. *///from www . j a v a2 s . co m private void unzip(String file) { final File fSourceZip = new File(file); try { final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (!entry.isDirectory()) { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte[] buffer = new byte[UltimateUpdater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, UltimateUpdater.BYTE_SIZE); while ((b = bis.read(buffer, 0, UltimateUpdater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginExists(name)) { File output = new File(updateFolder, name); destinationFilePath.renameTo(output); } } } zipFile.close(); // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. moveNewZipFiles(zipPath); } catch (final IOException e) { } finally { fSourceZip.delete(); } }
From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderAnyMemo.java
private void downloadDatabase(final DownloadItem di) throws Exception { String filename = di.getExtras("filename"); if (filename == null) { throw new Exception("Could not get filename"); }//from w w w. ja v a2 s . c o m String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath() + getString(R.string.default_dir); File outFile = new File(sdpath + filename); mHandler.post(new Runnable() { public void run() { mProgressDialog = new ProgressDialog(DownloaderAnyMemo.this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setMessage(getString(R.string.loading_downloading)); mProgressDialog.show(); } }); try { OutputStream out; if (outFile.exists()) { throw new IOException("Database already exist!"); } try { outFile.createNewFile(); out = new FileOutputStream(outFile); URL myURL = new URL(di.getAddress()); Log.v(TAG, "URL IS: " + myURL); URLConnection ucon = myURL.openConnection(); final int fileSize = ucon.getContentLength(); mHandler.post(new Runnable() { public void run() { mProgressDialog.setMax(fileSize); } }); byte[] buf = new byte[8192]; InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is, 8192); Runnable increaseProgress = new Runnable() { public void run() { mProgressDialog.setProgress(mDownloadProgress); } }; int len = 0; int lenSum = 0; while ((len = bis.read(buf)) != -1) { out.write(buf, 0, len); lenSum += len; if (lenSum > fileSize / 50) { /* This is tricky. * The UI thread can not be updated too often. * So we update it only 50 times */ mDownloadProgress += lenSum; lenSum = 0; mHandler.post(increaseProgress); } } out.close(); is.close(); /* Uncompress the zip file that contains images */ if (filename.endsWith(".zip")) { mHandler.post(new Runnable() { public void run() { mProgressDialog.setProgress(fileSize); mProgressDialog.setMessage(getString(R.string.downloader_extract_zip)); } }); BufferedOutputStream dest = null; BufferedInputStream ins = null; ZipEntry entry; ZipFile zipfile = new ZipFile(outFile); Enumeration<?> e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); Log.v(TAG, "Extracting: " + entry); if (entry.isDirectory()) { new File(sdpath + "/" + entry.getName()).mkdir(); } else { ins = new BufferedInputStream(zipfile.getInputStream(entry), 8192); int count; byte data[] = new byte[8192]; FileOutputStream fos = new FileOutputStream(sdpath + "/" + entry.getName()); dest = new BufferedOutputStream(fos, 8192); while ((count = ins.read(data, 0, 8192)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); ins.close(); } } /* Delete the zip file if it is successfully decompressed */ outFile.delete(); } /* We do not check ttf file as db */ if (!filename.toLowerCase().endsWith(".ttf")) { /* Check if the db is correct */ filename = filename.replace(".zip", ".db"); DatabaseHelper dh = new DatabaseHelper(DownloaderAnyMemo.this, sdpath, filename); dh.close(); } } catch (Exception e) { if (outFile.exists()) { outFile.delete(); } throw new Exception(e); } } catch (Exception e) { Log.e(TAG, "Error downloading", e); throw new Exception(e); } finally { mHandler.post(new Runnable() { public void run() { mProgressDialog.dismiss(); } }); } }
From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java
private void computeDuplicateFiles(File jar) throws IOException { ZipFile file = new ZipFile(jar); Enumeration<? extends ZipEntry> list = file.entries(); while (list.hasMoreElements()) { ZipEntry ze = list.nextElement(); if (!(ze.getName().contains("META-INF/") || ze.isDirectory())) { // Exclude META-INF and Directories List<File> l = jars.get(ze.getName()); if (l == null) { l = new ArrayList<File>(); jars.put(ze.getName(), l); }/*from ww w . j a v a 2s . c o m*/ l.add(jar); } } }
From source file:com.informatica.um.binge.api.impl.PluginsFactory.java
/** * Extract the zip file into the output folder * @param fileName - Name of the zip file * @param outFolderName - output folder name. * @throws Exception//from w w w . j a va2s . c o m */ protected Multimap<String, File> extractZipFile(String fileName, String outFolderName) throws Exception { LOG.debug("Going to extract zip file {} to folder {}", fileName, outFolderName); Multimap<String, File> deps = HashMultimap.create(2, 5); File outFolder = new File(outFolderName); ZipInputStream zipInput = new ZipInputStream(new FileInputStream(new File(fileName))); ZipEntry ze = null; boolean status = outFolder.mkdirs(); if (status) LOG.info("Successfully created plugin folder {}", outFolder.getAbsolutePath()); else { throw new VDSException(VDSErrorCode.PLUGIN_FOLDER_CREATE_ERROR, outFolder.getAbsolutePath()); } byte[] buffer = new byte[1024]; while ((ze = zipInput.getNextEntry()) != null) { String name = ze.getName(); // process files only if (ze.isDirectory() == false) { File file = new File(name); File newFile = null; if (file.getParentFile() != null && file.getParentFile().getName().equals(NATIVE)) { newFile = new File(nativeLibs, file.getName()); } else if (file.getParentFile() != null && file.getParentFile().getName().equals(LIB)) { newFile = Paths.get(outFolderName, LIB, file.getName()).toFile(); deps.put(LIB, newFile); } else { newFile = new File(outFolderName, file.getName()); if (name.endsWith(".jar")) deps.put(LIB, newFile); } newFile.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zipInput.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } } return deps; }
From source file:edu.isi.wings.portal.classes.StorageHandler.java
public static String unzipFile(File f, String todirname, String toDirectory) { File todir = new File(toDirectory); if (!todir.exists()) todir.mkdirs();/*w w w .ja va2s. co m*/ try { // Check if the zip file contains only one directory ZipFile zfile = new ZipFile(f); String topDir = null; boolean isOneDir = true; for (Enumeration<? extends ZipEntry> e = zfile.entries(); e.hasMoreElements();) { ZipEntry ze = e.nextElement(); String name = ze.getName().replaceAll("/.+$", ""); name = name.replaceAll("/$", ""); // OSX Zips carry an extra __MACOSX directory. Ignore it if (name.equals("__MACOSX")) continue; if (topDir == null) topDir = name; else if (!topDir.equals(name)) { isOneDir = false; break; } } zfile.close(); // Delete existing directory (if any) FileUtils.deleteDirectory(new File(toDirectory + File.separator + todirname)); // Unzip file(s) into toDirectory/todirname ZipInputStream zis = new ZipInputStream(new FileInputStream(f)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); // OSX Zips carry an extra __MACOSX directory. Ignore it if (fileName.startsWith("__MACOSX")) { ze = zis.getNextEntry(); continue; } // Get relative file path translated to 'todirname' if (isOneDir) fileName = fileName.replaceFirst(topDir, todirname); else fileName = todirname + File.separator + fileName; // Create directories File newFile = new File(toDirectory + File.separator + fileName); if (ze.isDirectory()) newFile.mkdirs(); else newFile.getParentFile().mkdirs(); try { // Copy file FileOutputStream fos = new FileOutputStream(newFile); IOUtils.copy(zis, fos); fos.close(); String mime = new Tika().detect(newFile); if (mime.equals("application/x-sh") || mime.startsWith("text/")) FileUtils.writeLines(newFile, FileUtils.readLines(newFile)); // Set all files as executable for now newFile.setExecutable(true); } catch (FileNotFoundException fe) { // Silently ignore //fe.printStackTrace(); } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); return toDirectory + File.separator + todirname; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:fr.paris.lutece.plugins.updater.service.UpdateService.java
/** * Extract a package/* w w w .j a v a2 s . c o m*/ * @param strZipFile The package zip file * @param strDirectory The target directory * @throws UpdaterDownloadException If an exception occurs during download */ private void extractPackage(String strZipFile, String strDirectory) throws UpdaterDownloadException { try { File file = new File(strZipFile); ZipFile zipFile = new ZipFile(file); // Each zipped file is indentified by a zip entry : Enumeration zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement(); // Clean the name : String strEntryName = zipEntry.getName(); // The unzipped file : File destFile = new File(strDirectory, strEntryName); // Create the parent directory structure if needed : destFile.getParentFile().mkdirs(); if (!zipEntry.isDirectory()) { // InputStream from zipped data InputStream inZipStream = null; try { AppLogService.debug("unzipping " + strEntryName + " to " + destFile.getName()); inZipStream = zipFile.getInputStream(zipEntry); // OutputStream to the destination file OutputStream outDestStream = new FileOutputStream(destFile); // Helper method to copy data copyStream(inZipStream, outDestStream); inZipStream.close(); outDestStream.close(); } catch (IOException e) { AppLogService.error("Error extracting file : " + e.getMessage(), e); } finally { try { inZipStream.close(); } catch (IOException e) { AppLogService.error("Error extracting file : " + e.getMessage(), e); } } } else { AppLogService.debug("skipping directory " + strEntryName); } } } catch (ZipException e) { AppLogService.error("Error extracting file : " + e.getMessage(), e); throw new UpdaterDownloadException("Error extracting package ", e); } catch (IOException e) { AppLogService.error("Error extracting file : " + e.getMessage(), e); } }
From source file:com.seer.datacruncher.services.ServiceScheduledJob.java
@Override protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException { long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); JobsEntity jobEntity = jobsDao.find(jobId); if (!jobEntity.isWorking()) { if (jobsDao.setWorkStatus(jobId, true)) { try { long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null ? -1l/*w w w . ja v a 2s .c o m*/ : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId")); if (eventTriggerId > 0) { EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId); String className = entity.getName(); try { String sourceCode = entity.getCode(); EventTrigger eventTrigger; String response; eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className, "com.seer.datacruncher.eventtrigger.EventTrigger", EventTrigger.class, sourceCode); assert eventTrigger != null; response = eventTrigger.trigger(); log.info("Response From EventTrigger(" + className + ") :" + response); } catch (Exception e) { e.printStackTrace(); log.error("EventTrigger(" + className + ") :" + e.getMessage(), e); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage()); } catch (NoClassDefFoundError err) { log.error("EventTrigger(" + className + ") :" + err.getMessage(), err); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage()); } return; } int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day")); int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month")); if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) { return; } StandardFileSystemManager fsManager = new StandardFileSystemManager(); boolean isDataStream = true; try { fsManager.init(); long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId"); long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId"); //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId"); String datastream = ""; int idSchemaType = schemasDao.find(schemaId).getIdSchemaType(); TasksEntity taskEntity = tasksDao.find(schedulerId); //JobsEntity jobEntity = jobsDao.find(jobId); if (taskEntity.getIsOneShoot()) { jobEntity.setIsActive(0); jobsDao.update(jobEntity); } if (idSchemaType == SchemaType.GENERATION) { StreamGenerationUtils sgu = new StreamGenerationUtils(); datastream = sgu.getStream(schemaId); log.debug("Content stream: " + schemaId); if (datastream.trim().length() > 0) { log.debug("Datastream to validate: " + datastream); DatastreamsInput datastreamsInput = new DatastreamsInput(); String result = datastreamsInput.datastreamsInput(datastream, schemaId, null); log.debug("Validation result: " + result); } else { isDataStream = false; log.debug("No datastream create"); } } if (connectionId != 0) { int serviceId = Integer .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId")); String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp"); String port = arg0.getJobDetail().getJobDataMap().getString("port"); String userName = arg0.getJobDetail().getJobDataMap().getString("userName"); String password = arg0.getJobDetail().getJobDataMap().getString("password"); String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory"); String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName"); ConnectionsEntity conn; conn = connectionsDao.find(connectionId); if (inputDirectory == null || inputDirectory.trim().length() == 0) { inputDirectory = fileName; } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn && serviceId == Servers.HTTP.getDbCode())) { inputDirectory = inputDirectory + "/" + fileName; } log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server [" + hostName + ":" + port + "] with user[" + userName + "]."); String url = ""; if (serviceId == Servers.SAMBA.getDbCode()) { if (!fsManager.hasProvider("smb")) { fsManager.addProvider("smb", new SmbFileProvider()); } url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.HTTP.getDbCode()) { if (!fsManager.hasProvider("http")) { fsManager.addProvider("http", new HttpFileProvider()); } url = "http://" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.FTP.getDbCode()) { if (!fsManager.hasProvider("ftp")) { fsManager.addProvider("ftp", new FtpFileProvider()); } url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } log.info("url:" + url); final FileObject fileObject = fsManager.resolveFile(url); if (conn.getIdConnType() == GenericType.DownloadTypeConn) { if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject .getContent().getLastModifiedTime()) { log.info("There is no New or Updated '" + fileName + "' file on server to validate. Returning ..."); return; } else { log.info("There is New or Updated '" + fileName + "' file on server to validate. Validating ..."); ConnectionsEntity connection = connectionsDao.find(connectionId); connection.setFileDateTime( new Date(fileObject.getContent().getLastModifiedTime())); ApplicationContext ctx = AppContext.getApplicationContext(); ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class)); if (connDao != null) { connDao.update(connection); } Map<String, byte[]> resultMap = new HashMap<String, byte[]>(); byte data[] = new byte[(int) fileObject.getContent().getSize()]; fileObject.getContent().getInputStream().read(data); resultMap.put(fileObject.getName().getBaseName(), data); Set<String> keySet = resultMap.keySet(); Iterator<String> itr = keySet.iterator(); while (itr.hasNext()) { String strFileName = itr.next(); String result = ""; try { Long longSchemaId = schemaId; SchemaEntity schemaEntity = schemasDao.find(longSchemaId); if (schemaEntity == null) { result = "No schema found in database with Id [" + longSchemaId + "]"; log.error(result); logDao.setErrorLogMessage(result); } else { if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) { // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one ZipInputStream inStream = null; try { inStream = new ZipInputStream( new ByteArrayInputStream(resultMap.get(fileName))); ZipEntry entry; while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) { if (!entry.isDirectory()) { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput .setUploadedFileName(entry.getName()); byte[] byteInput = IOUtils.toByteArray(inStream); result += datastreamsInput.datastreamsInput( new String(byteInput), longSchemaId, byteInput); } inStream.closeEntry(); } log.debug(result); } catch (IOException ex) { result = "Error occured during fetch records from ZIP file."; log.error(result); logDao.setErrorLogMessage(result); } finally { if (inStream != null) inStream.close(); } } else { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput.setUploadedFileName(strFileName); result = datastreamsInput.datastreamsInput( new String(resultMap.get(strFileName)), longSchemaId, resultMap.get(strFileName)); log.debug(result); } } } catch (Exception ex) { ex.printStackTrace(); result = "Exception occured during process the message for xml file " + strFileName + " Error - " + ex.getMessage(); log.error(result); logDao.setErrorLogMessage(result); } } } } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) { File uploadFile = File.createTempFile(fileName, ".tmp"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile)); bw.write(datastream); bw.flush(); bw.close(); } catch (IOException ioex) { log.error("Datastream file can't be created"); logDao.setErrorLogMessage("Datastream file can't be created"); return; } if (serviceId == Servers.HTTP.getDbCode()) { try { HttpClient httpclient = new HttpClient(); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); Part[] parts = new Part[] { new FilePart("file", uploadFile.getName(), uploadFile) }; method.setRequestEntity( new MultipartRequestEntity(parts, method.getParams())); method.setDoAuthentication(true); int statusCode = httpclient.executeMethod(method); String responseBody = new String(method.getResponseBody()); if (statusCode != HttpStatus.SC_OK) { throw new HttpException(method.getStatusLine().toString()); } else { System.out.println(responseBody); } method.releaseConnection(); } catch (Exception ex) { log.error("Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); } } else { try { FileObject localFileObject = fsManager .resolveFile(uploadFile.getAbsolutePath()); fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF); System.out.println("File uploaded at : " + new Date()); if (uploadFile.exists()) { uploadFile.delete(); } } catch (Exception ex) { log.error( "Exception occurred during uploading of file: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file: " + ex.getMessage()); } } } } } catch (Exception ex) { log.error("Error " + ": " + ex.getMessage()); } finally { fsManager.close(); } } finally { jobsDao.setWorkStatus(jobId, false); } } else { log.error("Can not set " + jobEntity.getName() + "working."); } } else { log.debug("Job " + jobEntity.getName() + " is working."); } }
From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java
/** * Copies the content of a Jar/Zip archive into the receiver archive. * <p/>An optional {@link IZipEntryFilter} allows to selectively choose which files * to copy over.// w ww . j a v a 2 s. c om * * @param input the {@link InputStream} for the Jar/Zip to copy. * @param filter the filter or <code>null</code> * @throws IOException * @throws SignedJarBuilder.IZipEntryFilter.ZipAbortException if the {@link IZipEntryFilter} filter indicated that the write * must be aborted. */ public void writeZip(InputStream input, IZipEntryFilter filter) throws IOException, IZipEntryFilter.ZipAbortException { ZipInputStream zis = new ZipInputStream(input); try { // loop on the entries of the intermediary package and put them in the final package. ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); // do not take directories or anything inside a potential META-INF folder. if (entry.isDirectory()) { continue; } // ignore some of the content in META-INF/ but not all if (name.startsWith("META-INF/")) { // ignore the manifest file. String subName = name.substring(9); if ("MANIFEST.MF".equals(subName)) { int count; ByteArrayOutputStream out = new ByteArrayOutputStream(); while ((count = zis.read(buffer)) != -1) { out.write(buffer, 0, count); } ByteArrayInputStream swapStream = new ByteArrayInputStream(out.toByteArray()); Manifest manifest = new Manifest(swapStream); mManifest.getMainAttributes().putAll(manifest.getMainAttributes()); continue; } // special case for Maven meta-data because we really don't care about them in apks. if (name.startsWith("META-INF/maven/")) { continue; } // check for subfolder int index = subName.indexOf('/'); if (index == -1) { // no sub folder, ignores signature files. if (subName.endsWith(".SF") || name.endsWith(".RSA") || name.endsWith(".DSA")) { continue; } } } // if we have a filter, we check the entry against it if (filter != null && !filter.checkEntry(name)) { continue; } JarEntry newEntry; // Preserve the STORED method of the input entry. if (entry.getMethod() == JarEntry.STORED) { newEntry = new JarEntry(entry); } else { // Create a new entry so that the compressed len is recomputed. newEntry = new JarEntry(name); } writeEntry(zis, newEntry); zis.closeEntry(); } } finally { zis.close(); } }