List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry isDirectory
public boolean isDirectory()
From source file:cz.muni.fi.xklinec.zipstream.App.java
/** * Entry point. //ww w.java 2 s . c om * * @param args * @throws FileNotFoundException * @throws IOException * @throws NoSuchFieldException * @throws ClassNotFoundException * @throws NoSuchMethodException */ public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchFieldException, ClassNotFoundException, NoSuchMethodException, InterruptedException { OutputStream fos = null; InputStream fis = null; if ((args.length != 0 && args.length != 2)) { System.err.println(String.format("Usage: app.jar source.apk dest.apk")); return; } else if (args.length == 2) { System.err.println( String.format("Will use file [%s] as input file and [%s] as output file", args[0], args[1])); fis = new FileInputStream(args[0]); fos = new FileOutputStream(args[1]); } else if (args.length == 0) { System.err.println(String.format("Will use file [STDIN] as input file and [STDOUT] as output file")); fis = System.in; fos = System.out; } final Deflater def = new Deflater(9, true); ZipArchiveInputStream zip = new ZipArchiveInputStream(fis); // List of postponed entries for further "processing". List<PostponedEntry> peList = new ArrayList<PostponedEntry>(6); // Output stream ZipArchiveOutputStream zop = new ZipArchiveOutputStream(fos); zop.setLevel(9); // Read the archive ZipArchiveEntry ze = zip.getNextZipEntry(); while (ze != null) { ZipExtraField[] extra = ze.getExtraFields(true); byte[] lextra = ze.getLocalFileDataExtra(); UnparseableExtraFieldData uextra = ze.getUnparseableExtraFieldData(); byte[] uextrab = uextra != null ? uextra.getLocalFileDataData() : null; // ZipArchiveOutputStream.DEFLATED // // Data for entry byte[] byteData = Utils.readAll(zip); byte[] deflData = new byte[0]; int infl = byteData.length; int defl = 0; // If method is deflated, get the raw data (compress again). if (ze.getMethod() == ZipArchiveOutputStream.DEFLATED) { def.reset(); def.setInput(byteData); def.finish(); byte[] deflDataTmp = new byte[byteData.length * 2]; defl = def.deflate(deflDataTmp); deflData = new byte[defl]; System.arraycopy(deflDataTmp, 0, deflData, 0, defl); } System.err.println(String.format( "ZipEntry: meth=%d " + "size=%010d isDir=%5s " + "compressed=%07d extra=%d lextra=%d uextra=%d " + "comment=[%s] " + "dataDesc=%s " + "UTF8=%s " + "infl=%07d defl=%07d " + "name [%s]", ze.getMethod(), ze.getSize(), ze.isDirectory(), ze.getCompressedSize(), extra != null ? extra.length : -1, lextra != null ? lextra.length : -1, uextrab != null ? uextrab.length : -1, ze.getComment(), ze.getGeneralPurposeBit().usesDataDescriptor(), ze.getGeneralPurposeBit().usesUTF8ForNames(), infl, defl, ze.getName())); final String curName = ze.getName(); // META-INF files should be always on the end of the archive, // thus add postponed files right before them if (curName.startsWith("META-INF") && peList.size() > 0) { System.err.println( "Now is the time to put things back, but at first, I'll perform some \"facelifting\"..."); // Simulate som evil being done Thread.sleep(5000); System.err.println("OK its done, let's do this."); for (PostponedEntry pe : peList) { System.err.println( "Adding postponed entry at the end of the archive! deflSize=" + pe.deflData.length + "; inflSize=" + pe.byteData.length + "; meth: " + pe.ze.getMethod()); pe.dump(zop, false); } peList.clear(); } // Capturing interesting files for us and store for later. // If the file is not interesting, send directly to the stream. if ("classes.dex".equalsIgnoreCase(curName) || "AndroidManifest.xml".equalsIgnoreCase(curName)) { System.err.println("### Interesting file, postpone sending!!!"); PostponedEntry pe = new PostponedEntry(ze, byteData, deflData); peList.add(pe); } else { // Write ZIP entry to the archive zop.putArchiveEntry(ze); // Add file data to the stream zop.write(byteData, 0, infl); zop.closeArchiveEntry(); } ze = zip.getNextZipEntry(); } // Cleaning up stuff zip.close(); fis.close(); zop.finish(); zop.close(); fos.close(); System.err.println("THE END!"); }
From source file:com.zimbra.cs.util.ZipUtil.java
/** * Traditional java.util.zip processing either assumes archives use UTF-8 for filenames or requires that * you know up front what charset is used for filenames. * This class uses the more versatile org.apache.commons.compress.archivers.zip package combined with * language information to make a best guess at what the filenames might be. * *//*from w w w . j av a 2s.c o m*/ public static List<String> getZipEntryNames(InputStream inputStream, Locale locale) throws IOException { List<String> zipEntryNames = Lists.newArrayList(); /* * From http://commons.apache.org/proper/commons-compress/zip.html * Traditionally the ZIP archive format uses CodePage 437 as encoding for file name, which is not sufficient for * many international character sets. Over time different archivers have chosen different ways to work around * the limitation - the java.util.zip packages simply uses UTF-8 as its encoding for example. * * For our purposes, CP437 has the advantage that all byte sequences are valid, so it works well as a final * fallback charset to assume for the name. */ try (ZipArchiveInputStream zis = new ZipArchiveInputStream(inputStream, cp437charset.name(), false /* useUnicodeExtraFields - we do our own handling of this */)) { ZipArchiveEntry ze; while ((ze = zis.getNextZipEntry()) != null) { if (ze.isDirectory()) { continue; } String entryName = bestGuessAtEntryName(ze, locale); zipEntryNames.add(entryName); } } return zipEntryNames; }
From source file:com.android.tradefed.util.ZipUtil2.java
/** * Utility method to extract entire contents of zip file into given directory * * @param zipFile the {@link ZipFile} to extract * @param destDir the local dir to extract file to * @throws IOException if failed to extract file *//*from w w w . j a v a 2 s.com*/ public static void extractZip(ZipFile zipFile, File destDir) throws IOException { Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); File childFile = new File(destDir, entry.getName()); childFile.getParentFile().mkdirs(); if (entry.isDirectory()) { childFile.mkdirs(); applyUnixModeIfNecessary(entry, childFile); continue; } else { FileUtil.writeToFile(zipFile.getInputStream(entry), childFile); applyUnixModeIfNecessary(entry, childFile); } } }
From source file:com.zimbra.cs.util.ZipUtil.java
/** * * @param inputStream archive input stream * @param locale - best guess as to locale for the filenames in the archive * @param seqNo - the order of the item to return (excluding directory entries) * @return// w ww. j av a 2 s . c o m * @throws IOException */ public static ZipNameAndSize getZipEntryNameAndSize(InputStream inputStream, Locale locale, int seqNo) throws IOException { ZipArchiveInputStream zis = new ZipArchiveInputStream(inputStream, cp437charset.name(), false /* useUnicodeExtraFields - we do our own handling of this */); ZipArchiveEntry ze; int idx = 0; while ((ze = zis.getNextZipEntry()) != null) { if (ze.isDirectory()) { continue; } if (idx++ == seqNo) { String entryName = bestGuessAtEntryName(ze, locale); return new ZipNameAndSize(entryName, ze.getSize(), zis); } } zis.close(); throw new IOException("file " + seqNo + " not in archive"); }
From source file:aiai.apps.commons.utils.ZipUtils.java
/** * Unzips a zip file into the given destination directory. * * The archive file MUST have a unique "root" folder. This root folder is * skipped when unarchiving./*from w w w .ja v a 2 s . com*/ * */ public static void unzipFolder(File archiveFile, File zipDestinationFolder) { log.debug("Start unzipping archive file"); log.debug("'\tzip archive file: {}", archiveFile.getAbsolutePath()); log.debug("'\t\tis exist: {}", archiveFile.exists()); log.debug("'\t\tis writable: {}", archiveFile.canWrite()); log.debug("'\t\tis readable: {}", archiveFile.canRead()); log.debug("'\ttarget dir: {}", zipDestinationFolder.getAbsolutePath()); log.debug("'\t\tis exist: {}", zipDestinationFolder.exists()); log.debug("'\t\tis writable: {}", zipDestinationFolder.canWrite()); try (MyZipFile zipFile = new MyZipFile(archiveFile)) { Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry zipEntry = entries.nextElement(); log.debug("'\t\tzip entry: {}, is directory: {}", zipEntry.getName(), zipEntry.isDirectory()); String name = zipEntry.getName(); if (zipEntry.isDirectory()) { if (name.endsWith("/") || name.endsWith("\\")) { name = name.substring(0, name.length() - 1); } File newDir = new File(zipDestinationFolder, name); log.debug("'\t\t\tcreate dirs in {}", newDir.getAbsolutePath()); if (!newDir.mkdirs()) { throw new RuntimeException("Creation of target dir was failed, target dir: " + zipDestinationFolder + ", entity: " + name); } } else { File destinationFile = DirUtils.createTargetFile(zipDestinationFolder, name); if (destinationFile == null) { throw new RuntimeException("Creation of target file was failed, target dir: " + zipDestinationFolder + ", entity: " + name); } if (!destinationFile.getParentFile().exists()) { destinationFile.getParentFile().mkdirs(); } log.debug("'\t\t\tcopy content of zip entry to file {}", destinationFile.getAbsolutePath()); FileUtils.copyInputStreamToFile(zipFile.getInputStream(zipEntry), destinationFile); } } } catch (IOException e) { throw new RuntimeException("Unzip failed:", e); } }
From source file:com.amazonaws.codepipeline.jenkinsplugin.ExtractionTools.java
private static void extractZipFile(final File destination, final ZipFile zipFile) throws IOException { final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { final ZipArchiveEntry entry = entries.nextElement(); final File entryDestination = getDestinationFile(destination, entry.getName()); if (entry.isDirectory()) { entryDestination.mkdirs();//from w w w.j ava2 s . co m } else { entryDestination.getParentFile().mkdirs(); final InputStream in = zipFile.getInputStream(entry); try (final OutputStream out = new FileOutputStream(entryDestination)) { IOUtils.copy(in, out); IOUtils.closeQuietly(in); } } } }
From source file:com.silverpeas.util.ZipManager.java
/** * Indicates the number of files (not directories) inside the archive. * * @param archive the archive whose content is analyzed. * @return the number of files (not directories) inside the archive. *//*from w w w. j a va2s . c o m*/ public static int getNbFiles(File archive) { ZipFile zipFile = null; int nbFiles = 0; try { zipFile = new ZipFile(archive); @SuppressWarnings("unchecked") Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry ze = entries.nextElement(); if (!ze.isDirectory()) { nbFiles++; } } } catch (IOException ioe) { SilverTrace.warn("util", "ZipManager.getNbFiles()", "util.EXE_ERROR_WHILE_COUNTING_FILE", "sourceFile = " + archive.getPath(), ioe); } finally { if (zipFile != null) { ZipFile.closeQuietly(zipFile); } } return nbFiles; }
From source file:com.googlecode.t7mp.util.ZipUtil.java
public static void unzip(InputStream warInputStream, File destination) { try {/* w w w. j a v a2 s .co m*/ ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(warInputStream); ZipArchiveEntry entry = null; while ((entry = in.getNextZipEntry()) != null) { File outfile = new File(destination.getCanonicalPath() + "/" + entry.getName()); outfile.getParentFile().mkdirs(); if (entry.isDirectory()) { outfile.mkdir(); continue; } OutputStream o = new FileOutputStream(outfile); try { IOUtils.copy(in, o); } finally { o.close(); } } } finally { if (in != null) { in.close(); } } warInputStream.close(); } catch (FileNotFoundException e) { throw new TomcatSetupException(e.getMessage(), e); } catch (IOException e) { throw new TomcatSetupException(e.getMessage(), e); } }
From source file:com.igormaznitsa.zxpoly.utils.ROMLoader.java
public static RomData getROMFrom(final String url) throws IOException { final URI uri; try {//from w ww. j a v a 2 s . c o m uri = new URI(url); } catch (URISyntaxException ex) { throw new IOException("Error in URL '" + url + "\'", ex); } final String scheme = uri.getScheme(); final String userInfo = uri.getUserInfo(); final String name; final String password; if (userInfo != null) { final String[] splitted = userInfo.split("\\:"); name = splitted[0]; password = splitted[1]; } else { name = null; password = null; } final byte[] loaded; if (scheme.startsWith("http")) { loaded = loadHTTPArchive(url); } else if (scheme.startsWith("ftp")) { loaded = loadFTPArchive(uri.getHost(), uri.getPath(), name, password); } else { throw new IllegalArgumentException("Unsupported scheme [" + scheme + ']'); } final ZipArchiveInputStream in = new ZipArchiveInputStream(new ByteArrayInputStream(loaded)); byte[] rom48 = null; byte[] rom128 = null; byte[] romTrDos = null; while (true) { final ZipArchiveEntry entry = in.getNextZipEntry(); if (entry == null) { break; } if (entry.isDirectory()) { continue; } if (ROM_48.equalsIgnoreCase(entry.getName())) { final int size = (int) entry.getSize(); if (size > 16384) { throw new IOException("ROM 48 has too big size"); } rom48 = new byte[16384]; IOUtils.readFully(in, rom48, 0, size); } else if (ROM_128TR.equalsIgnoreCase(entry.getName())) { final int size = (int) entry.getSize(); if (size > 16384) { throw new IOException("ROM 128TR has too big size"); } rom128 = new byte[16384]; IOUtils.readFully(in, rom128, 0, size); } else if (ROM_TRDOS.equalsIgnoreCase(entry.getName())) { final int size = (int) entry.getSize(); if (size > 16384) { throw new IOException("ROM TRDOS has too big size"); } romTrDos = new byte[16384]; IOUtils.readFully(in, romTrDos, 0, size); } } if (rom48 == null) { throw new IOException(ROM_48 + " not found"); } if (rom128 == null) { throw new IOException(ROM_128TR + " not found"); } if (romTrDos == null) { throw new IOException(ROM_TRDOS + " not found"); } return new RomData(rom48, rom128, romTrDos); }
From source file:com.ALC.SC2BOAserver.util.SC2BOAserverFileUtil.java
/** * This method extracts data to a given directory. * //from w ww .ja v a 2 s. co m * @param directory the directory to extract into * @param zipIn input stream pointing to the zip file * @throws ArchiveException * @throws IOException * @throws FileNotFoundException */ public static void extractZipToDirectory(File directory, InputStream zipIn) throws ArchiveException, IOException, FileNotFoundException { ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", zipIn); while (true) { ZipArchiveEntry entry = (ZipArchiveEntry) in.getNextEntry(); if (entry == null) { in.close(); break; } //Skip empty files if (entry.getName().equals("")) { continue; } if (entry.isDirectory()) { File file = new File(directory, entry.getName()); file.mkdirs(); } else { File outFile = new File(directory, entry.getName()); if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdirs(); } OutputStream out = new FileOutputStream(outFile); IOUtils.copy(in, out); out.flush(); out.close(); } } }