Example usage for java.util.zip ZipFile ZipFile

List of usage examples for java.util.zip ZipFile ZipFile

Introduction

In this page you can find the example usage for java.util.zip ZipFile ZipFile.

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:dk.deck.resolver.util.ZipUtils.java

public List<String> listArchive(File archive) {
    List<String> paths = new ArrayList<String>();
    try {/*from   w  w  w  .  j ava 2s  .  c om*/
        ZipFile zipfile = new ZipFile(archive);
        for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            paths.add(entry.getName());
        }
        zipfile.close();
    } catch (Exception e) {
        log.error("Error while extracting file " + archive, e);
    }

    return paths;
}

From source file:com.shazam.fork.TestClassScanner.java

private static void getDexClassesFromApk(File apkFile, File outputFolder) {
    ZipFile zip = null;/*www.j  ava  2 s .c  o  m*/
    InputStream classesDexInputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
        zip = new ZipFile(apkFile);

        int index = 1;
        String currentDex;
        while (true) {
            currentDex = CLASSES_PREFIX + (index > 1 ? index : "") + DEX_EXTENSION;
            ZipEntry classesDex = zip.getEntry(currentDex);
            if (classesDex != null) {
                File dexFileDestination = new File(outputFolder, currentDex);
                classesDexInputStream = zip.getInputStream(classesDex);
                fileOutputStream = new FileOutputStream(dexFileDestination);
                copyLarge(classesDexInputStream, fileOutputStream);
                index++;
            } else {
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeQuietly(classesDexInputStream);
        closeQuietly(fileOutputStream);
        closeZipQuietly(zip);
    }
}

From source file:com.pieframework.runtime.utils.Zipper.java

public static void unzip(String zipFile, String toDir) throws ZipException, IOException {

    int BUFFER = 2048;
    File file = new File(zipFile);

    ZipFile zip = new ZipFile(file);
    String newPath = toDir;/*from   w  w  w . ja v  a 2 s.  c om*/

    File toDirectory = new File(newPath);
    if (!toDirectory.exists()) {
        toDirectory.mkdir();
    }
    Enumeration zipFileEntries = zip.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();
        File destFile = new File(newPath, FilenameUtils.separatorsToSystem(currentEntry));
        //System.out.println(currentEntry);
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
            int currentByte;
            // establish buffer for writing file
            byte data[] = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            // read and write until last byte is encountered
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, currentByte);
            }
            dest.flush();
            dest.close();
            is.close();
        }
    }
    zip.close();

}

From source file:b2s.idea.mavenize.JarCombiner.java

private static void copyContentsOf(File input, ZipOutputStream output, JarContext context) throws IOException {
    ZipFile zip = null;/*from ww w. j  av a  2 s.  c  o m*/
    try {
        zip = new ZipFile(input);
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (fileCanBeIgnored(entry, context)) {
                continue;
            }

            if (isServiceEntry(entry)) {
                context.addService(entry.getName(), contentsOf(entry, zip));
                continue;
            }

            output.putNextEntry(new ZipEntry(entry.getName()));
            output.write(contentsOf(entry, zip));
            output.flush();
            output.closeEntry();

            context.addVisitedEntry(entry);
        }
    } finally {
        close(zip);
    }
}

From source file:com.arrggh.eve.api.sde.StaticDataExportImporter.java

public void importFile(File zipFile) throws IOException {
    try (ZipFile sdeZip = new ZipFile(zipFile)) {
        Map<Long, Type> types = processMap("Types",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/typeIDs.yaml")), Types.TYPE_MAP);

        List<InventoryType> items = processArray("Items",
                sdeZip.getInputStream(sdeZip.getEntry("sde/bsd/invItems.yaml")), Types.INVENTORY_TYPE_ARRAY);

        Map<Long, Blueprint> blueprints = processMap("Blueprint",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/blueprints.yaml")), Types.BLUEPRINT_MAP);

        for (ZipEntry entry : Collections.list(sdeZip.entries())) {
            String entryName = entry.getName();
            if (entryName.contains("sde/fsd/universe") && entryName.endsWith(".staticdata")) {
                if (entryName.endsWith("constellation.staticdata")) {
                    Constellation constellation = process(sdeZip.getInputStream(entry),
                            Types.CONSTELLATION_TYPE);
                }//from   w ww. j  a v  a2  s.  com
                if (entryName.endsWith("solarsystem.staticdata")) {
                    SolarSystem solarsystem = process(sdeZip.getInputStream(entry), Types.SOLARSYSTEM_TYPE);
                }
            }
        }

        Map<Long, Icon> icons = processMap("Icons",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/iconIDs.yaml")), Types.ICON_MAP);
        Map<Long, Graphic> graphics = processMap("Graphics",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/graphicIDs.yaml")), Types.GRAPHICS_MAP);
        Map<Long, Certificate> certificates = processMap("Certificates",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/certificates.yaml")), Types.CERTIFICATE_MAP);
        Map<Long, Group> groups = processMap("Groups",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/groupIDs.yaml")), Types.GROUPS_MAP);
        Map<Long, Category> categories = processMap("Categories",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/categoryIDs.yaml")), Types.CATEGORY_MAP);
        Map<Long, SkinLicense> skinLicenses = processMap("Skin Licenses",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/skinLicenses.yaml")), Types.SKIN_LICENCE_MAP);
        Map<Long, SkinMaterial> skinMaterials = processMap("Skin Materials",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/skinMaterials.yaml")), Types.SKIN_MATERIAL_MAP);
        Map<Long, Skin> skins = processMap("Skins",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/skins.yaml")), Types.SKIN_MAP);
        List<TournamentRuleSet> tournamentRuleSets = processArray("Tournament Rule Sets",
                sdeZip.getInputStream(sdeZip.getEntry("sde/fsd/tournamentRuleSets.yaml")),
                Types.TOURNAMENT_RULE_SET_ARRAY);
    }
}

From source file:asciidoc.maven.plugin.tools.ZipHelper.java

public File unzipEntry(File _zipFile, String _name) {
    File directory = null;/* ww  w. jav  a 2s. c o m*/
    try {
        if (this.log.isDebugEnabled())
            this.log.debug("zip file: " + _zipFile.getAbsolutePath());
        ZipEntry zipEntry = null;
        String zipEntryName = null;
        ZipFile jarZipFile = new ZipFile(_zipFile);
        Enumeration<? extends ZipEntry> e = jarZipFile.entries();
        while (e.hasMoreElements()) {
            zipEntry = (ZipEntry) e.nextElement();
            zipEntryName = zipEntry.getName();
            if (zipEntryName.startsWith(_name) && zipEntryName.endsWith(".zip")) {
                if (this.log.isInfoEnabled())
                    this.log.info("Found in " + zipEntryName);
                directory = new File(_zipFile.getParent(), FilenameUtils.removeExtension(zipEntryName));
                break;
            }
        }
        if (directory != null && !directory.exists()) {
            unzipEntry(jarZipFile, zipEntry, _zipFile.getParentFile());
            File asciiDocArchive = new File(_zipFile.getParent(), zipEntryName);
            unzipArchive(asciiDocArchive, _zipFile.getParentFile());
            asciiDocArchive.deleteOnExit();
        }

    } catch (ZipException ze) {
        this.log.error(ze.getMessage(), ze);
    } catch (IOException ioe) {
        this.log.error(ioe.getMessage(), ioe);
    }
    return directory;
}

From source file:org.cloudfoundry.client.lib.UploadApplicationPayloadTest.java

@Test
public void shouldPackOnlyMissingResources() throws Exception {
    ZipFile zipFile = new ZipFile(SampleProjects.springTravel());
    try {/*w  w  w .  j  a va  2 s .co m*/
        ApplicationArchive archive = new ZipApplicationArchive(zipFile);
        CloudResources allResources = new CloudResources(archive);
        List<CloudResource> resources = new ArrayList<CloudResource>(allResources.asList());
        resources.remove(0);
        CloudResources knownRemoteResources = new CloudResources(resources);
        UploadApplicationPayload payload = new UploadApplicationPayload(archive, knownRemoteResources);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        FileCopyUtils.copy(payload.getInputStream(), bos);
        assertThat(payload.getArchive(), is(archive));
        assertThat(payload.getTotalUncompressedSize(), is(93));
        assertThat(bos.toByteArray().length, is(2451));
    } finally {
        zipFile.close();
    }
}

From source file:kr.ac.kaist.swrc.jhannanum.share.JSONZipReader.java

/**
 * read JSON file from JAR file.//from   w  w w  .  j a  v a2s  .  c  om
 * @return Length of JSON Keys
 * @throws JSONException, IOException
 */

protected int read() throws JSONException, IOException {
    ZipFile zip = new ZipFile(zipFilePath);
    ZipEntry entry = zip.getEntry(jsonFile);
    InputStream in = zip.getInputStream(entry);
    this.json = read(in);
    zip.close();
    return json.length();
}

From source file:com.google.gdt.eclipse.designer.webkit.WebKitSupportWin32.java

public static void deployIfNeededAndLoad() {
    if (!m_initialized) {
        try {/*  w ww. j a va 2  s .co m*/
            // extract
            Bundle bundle = Platform.getBundle("com.google.gdt.eclipse.designer.hosted.2_0.webkit");
            URL resource = FileLocator.resolve(bundle.getResource("WebKit.zip"));
            ZipFile zipFile = new ZipFile(resource.getPath());
            try {
                if (deployNeeded(zipFile)) {
                    extract(zipFile);
                }
            } finally {
                zipFile.close();
            }
            load();
            m_available = true;
        } catch (Throwable e) {
            // ignore
        }
        m_initialized = true;
    }
}

From source file:cz.lbenda.common.ClassLoaderHelper.java

@SuppressWarnings("unchecked")
public static List<String> instancesOfClass(Class clazz, List<String> libs, boolean abstractClass,
        boolean interf) {
    List<String> classNames = new ArrayList<>();
    ClassLoader clr = createClassLoader(libs, false);
    List<String> result = new ArrayList<>();
    libs.forEach(lib -> {/*from   w  w  w  .  j  a  v a 2 s.  co m*/
        try (ZipFile file = new ZipFile(lib)) {
            file.stream().forEach(entry -> {
                if (entry.getName().equals("META-INF/services/" + clazz.getName())) {
                    try {
                        String string = IOUtils.toString(file.getInputStream(entry));
                        String[] lines = string.split("\n");
                        for (String line : lines) {
                            result.add(line.trim());
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } else if (entry.getName().endsWith(".class")) {
                    String className = entry.getName().substring(0, entry.getName().length() - 6).replace("/",
                            ".");
                    classNames.add(className);
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    classNames.forEach(cc -> {
        try {
            Class cla = clr.loadClass(cc);
            if ((interf || !cla.isInterface()) && (abstractClass || !Modifier.isAbstract(cla.getModifiers()))
                    && clazz.isAssignableFrom(cla)) {
                if (!result.contains(cc)) {
                    result.add(cc);
                }
            }
        } catch (ClassNotFoundException | NoClassDefFoundError e) {
            /* It's common to try to create class which haven't class which need*/ }
    });
    return result;
}