Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName.

Prototype

public String getName() 

Source Link

Document

Get the name of the entry.

Usage

From source file:cz.muni.fi.xklinec.zipstream.App.java

/**
 * Entry point. /*  www  .ja v a2  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.hw.util.CompressUtils.java

private static void unzipFolder(File uncompressFile, File descPathFile, boolean override) {

    ZipFile zipFile = null;/*from w  w w  . j a v a 2 s  . c  om*/
    try {
        zipFile = new ZipFile(uncompressFile, "GBK");

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zipEntry = entries.nextElement();
            String name = zipEntry.getName();
            name = name.replace("\\", "/");

            File currentFile = new File(descPathFile, name);

            //? 
            if (currentFile.isFile() && currentFile.exists() && !override) {
                continue;
            }

            if (name.endsWith("/")) {
                currentFile.mkdirs();
                continue;
            } else {
                currentFile.getParentFile().mkdirs();
            }

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(currentFile);
                InputStream is = zipFile.getInputStream(zipEntry);
                IOUtils.copy(is, fos);
            } finally {
                IOUtils.closeQuietly(fos);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("", e);
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
            }
        }
    }

}

From source file:com.daphne.es.maintain.editor.web.controller.utils.CompressUtils.java

@SuppressWarnings("unchecked")
private static void unzipFolder(File uncompressFile, File descPathFile, boolean override) {

    ZipFile zipFile = null;/*  ww w  . j a  v a 2s. co m*/
    try {
        zipFile = new ZipFile(uncompressFile, "GBK");

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zipEntry = entries.nextElement();
            String name = zipEntry.getName();
            name = name.replace("\\", "/");

            File currentFile = new File(descPathFile, name);

            //? 
            if (currentFile.isFile() && currentFile.exists() && !override) {
                continue;
            }

            if (name.endsWith("/")) {
                currentFile.mkdirs();
                continue;
            } else {
                currentFile.getParentFile().mkdirs();
            }

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(currentFile);
                InputStream is = zipFile.getInputStream(zipEntry);
                IOUtils.copy(is, fos);
            } finally {
                IOUtils.closeQuietly(fos);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("", e);
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
            }
        }
    }

}

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 ww  . j av  a2 s  .c om
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.googlecode.t7mp.util.ZipUtil.java

public static void unzip(InputStream warInputStream, File destination) {
    try {//from   w  ww  .j  ava2  s .  c o  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.chnoumis.commons.zip.utils.ZipUtils.java

public static void unZip(InputStream is) throws ArchiveException, IOException {
    ArchiveInputStream in = null;/*www.j  ava2s  .co  m*/
    try {
        in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
        ZipArchiveEntry entry = null;
        while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) {
            OutputStream o = new FileOutputStream(entry.getName());
            try {
                IOUtils.copy(in, o);
            } finally {
                o.close();
            }
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
    is.close();
}

From source file:big.zip.java

/**
 * When given a zip file, this method will open it up and extract all files
 * inside into a specific folder on disk. Typically on BIG archives, the zip
 * file only contains a single file with the original file name.
 * @param fileZip           The zip file that we want to extract files from
 * @param folderToExtract   The folder where the extract file will be placed 
 * @return True if no problems occurred, false otherwise
 */// www  . ja v a 2s.  c  o m
public static boolean extract(final File fileZip, final File folderToExtract) {
    // preflight check
    if (fileZip.exists() == false) {
        System.out.println("ZIP126 - Zip file not found: " + fileZip.getAbsolutePath());
        return false;
    }
    // now proceed to extract the files
    try {
        final InputStream inputStream = new FileInputStream(fileZip);
        final ArchiveInputStream ArchiveStream;
        ArchiveStream = new ArchiveStreamFactory().createArchiveInputStream("zip", inputStream);
        final ZipArchiveEntry entry = (ZipArchiveEntry) ArchiveStream.getNextEntry();
        final OutputStream outputStream = new FileOutputStream(new File(folderToExtract, entry.getName()));
        IOUtils.copy(ArchiveStream, outputStream);

        // flush and close all files
        outputStream.flush();
        outputStream.close();
        ArchiveStream.close();
        inputStream.close();
    } catch (ArchiveException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
    }
    return true;
}

From source file:com.ALC.SC2BOAserver.util.SC2BOAserverFileUtil.java

/**
 * This method extracts data to a given directory.
 * //  w  w w . j a  v  a 2  s  . c  o  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();
        }
    }
}

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 ww .ja  v  a 2s. com
        } 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: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  va  2  s. co m
 *
 */
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);
    }
}