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:ch.ivyteam.ivy.maven.TestIarPackagingMojo.java

/**
 * Happy path creation tests/*from w  ww  .  j a  va 2 s  .co  m*/
 * @throws Exception
 */
@Test
public void archiveCreationDefault() throws Exception {
    IarPackagingMojo mojo = rule.getMojo();
    File svn = new File(mojo.project.getBasedir(), ".svn/svn.txt");
    FileUtils.write(svn, "svn");
    mojo.execute();
    Collection<File> iarFiles = FileUtils.listFiles(new File(mojo.project.getBasedir(), "target"),
            new String[] { "iar" }, false);
    assertThat(iarFiles).hasSize(1);

    File iarFile = iarFiles.iterator().next();
    assertThat(iarFile.getName()).isEqualTo("base-1.0.0.iar");
    assertThat(mojo.project.getArtifact().getFile())
            .as("Created IAR must be registered as artifact for later repository installation.")
            .isEqualTo(iarFile);

    try (ZipFile archive = new ZipFile(iarFile)) {
        assertThat(archive.getEntry(".classpath")).as(".classpath must be packed for internal binary retrieval")
                .isNotNull();
        assertThat(archive.getEntry("src_hd")).as("Empty directories should be included (by default) "
                + "so that the IAR can be re-imported into the designer").isNotNull();
        assertThat(archive.getEntry("target/sampleOutput.txt")).as("'target' folder should not be packed")
                .isNull();
        assertThat(archive.getEntry("target")).as("'target'folder should not be packed").isNull();
        assertThat(archive.getEntry(".svn/svn.txt")).as("'.svn' folder should not be packed").isNull();
        assertThat(archive.getEntry(".svn")).as("'target'.svn should not be packed").isNull();
        assertThat(archive.getEntry("classes/gugus.txt")).as("classes content should be included by default")
                .isNotNull();
    }
}

From source file:br.univali.celine.lms.utils.zip.Zip.java

public void unzip(File zipFile, File dir) throws Exception {

    InputStream is = null;// w w  w  .ja  va 2  s . c  o  m
    OutputStream os = null;
    ZipFile zip = null;

    try {

        zip = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> e = zip.entries();

        byte[] buffer = new byte[2048];
        int currentEntry = 0;

        while (e.hasMoreElements()) {

            ZipEntry zipEntry = (ZipEntry) e.nextElement();
            File file = new File(dir, zipEntry.getName());
            currentEntry++;

            if (zipEntry.isDirectory()) {

                if (!file.exists())
                    file.mkdirs();

                continue;

            }

            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();

            try {

                int bytesLidos = 0;

                is = zip.getInputStream(zipEntry);
                os = new FileOutputStream(file);

                if (is == null)
                    throw new ZipException("Erro ao ler a entrada do zip: " + zipEntry.getName());

                while ((bytesLidos = is.read(buffer)) > 0)
                    os.write(buffer, 0, bytesLidos);

                if (listener != null)
                    listener.unzip((100 * currentEntry) / zip.size());

            } finally {

                if (is != null)
                    try {
                        is.close();
                    } catch (Exception ex) {
                    }

                if (os != null)
                    try {
                        os.close();
                    } catch (Exception ex) {
                    }

            }
        }

    } finally {

        if (zip != null)
            try {
                zip.close();
            } catch (Exception e) {
            }

    }

}

From source file:com.openkm.util.DocumentUtils.java

/**
 * Text spell checker/*from  w w w  . ja  va2 s.  c  o  m*/
 */
public static String spellChecker(String text) throws IOException {
    log.debug("spellChecker({})", text);
    StringBuilder sb = new StringBuilder();

    if (Config.SYSTEM_OPENOFFICE_DICTIONARY.equals("")) {
        log.warn("OpenOffice dictionary not configured");
        sb.append(text);
    } else {
        log.info("Using OpenOffice dictionary: {}", Config.SYSTEM_OPENOFFICE_DICTIONARY);
        ZipFile zf = new ZipFile(Config.SYSTEM_OPENOFFICE_DICTIONARY);
        OpenOfficeSpellDictionary oosd = new OpenOfficeSpellDictionary(zf);
        SpellChecker sc = new SpellChecker(oosd);
        sc.setCaseSensitive(false);
        StringTokenizer st = new StringTokenizer(text);

        while (st.hasMoreTokens()) {
            String w = st.nextToken();
            List<String> s = sc.getDictionary().getSuggestions(w);

            if (s.isEmpty()) {
                sb.append(w).append(" ");
            } else {
                sb.append(s.get(0)).append(" ");
            }
        }

        zf.close();
    }

    log.debug("spellChecker: {}", sb.toString());
    return sb.toString();
}

From source file:com.dclab.preparation.ReadTest.java

public void dig(File folder) {
    File[] files = folder.listFiles();
    Logger.getAnonymousLogger().info("OPENING folder " + folder.getName());
    Map<Boolean, List<File>> isZip = Arrays.stream(files)
            .collect(Collectors.partitioningBy((f -> f.getName().endsWith("zip"))));
    Map<Boolean, List<File>> isFolder = isZip.get(false).stream()
            .collect(Collectors.partitioningBy(f -> f.isDirectory()));
    isFolder.get(false).stream().filter(y -> y.getName().endsWith("xml")).forEach(this::scanFile);
    isFolder.get(true).stream().forEach(this::dig);
    isZip.get(true).stream().forEach(z -> {
        try {/* w w w . ja  v a  2  s .c  o m*/
            ZipFile zipFile = new ZipFile(z);
            zipFile.stream().forEach(ze -> {
                try {
                    String s = handleZip(zipFile, ze);
                    if (s != null) {
                        printLine(s);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(ReadTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            });
        } catch (IOException ex) {
            Logger.getLogger(ReadTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    });

}

From source file:com.heliosdecompiler.helios.transformers.decompilers.KrakatauDecompiler.java

public boolean decompile(ClassNode classNode, byte[] bytes, StringBuilder output) {
    if (Helios.ensurePython2Set()) {
        if (Helios.ensureJavaRtSet()) {
            File inputJar = null;
            File outputJar = null;
            ZipFile zipFile = null;
            Process createdProcess;
            String log = "";

            try {
                inputJar = Files.createTempFile("kdein", ".jar").toFile();
                outputJar = Files.createTempFile("kdeout", ".zip").toFile();
                Map<String, byte[]> loadedData = Helios.getAllLoadedData();
                loadedData.put(classNode.name + ".class", bytes);
                Utils.saveClasses(inputJar, loadedData);

                createdProcess = Helios.launchProcess(new ProcessBuilder(
                        com.heliosdecompiler.helios.Settings.PYTHON2_LOCATION.get().asString(), "-O",
                        "decompile.py", "-skip", "-nauto",
                        Settings.MAGIC_THROW.isEnabled() ? "-xmagicthrow" : "", "-path", buildPath(inputJar),
                        "-out", outputJar.getAbsolutePath(), classNode.name + ".class")
                                .directory(Constants.KRAKATAU_DIR));

                log = Utils.readProcess(createdProcess);

                System.out.println(log);

                zipFile = new ZipFile(outputJar);
                ZipEntry zipEntry = zipFile.getEntry(classNode.name + ".java");
                if (zipEntry == null)
                    throw new IllegalArgumentException("Class failed to decompile (no class in output zip)");
                InputStream inputStream = zipFile.getInputStream(zipEntry);
                byte[] data = IOUtils.toByteArray(inputStream);
                output.append(new String(data, "UTF-8"));
                return true;
            } catch (Exception e) {
                output.append(parseException(e)).append("\n").append(log);
                return false;
            } finally {
                IOUtils.closeQuietly(zipFile);
                FileUtils.deleteQuietly(inputJar);
                FileUtils.deleteQuietly(outputJar);
            }/*from  www. ja v  a  2s  .  c  o m*/
        } else {
            output.append("You need to set the location of rt.jar");
        }
    } else {
        output.append("You need to set the location of Python 2.x");
    }
    return false;
}

From source file:at.ac.tuwien.big.testsuite.impl.task.UnzipTaskImpl.java

private void unzip(File zipFile, File baseDirectory, boolean extractContainedZipFiles,
        Collection<Exception> exceptions) {
    try (ZipFile zip = new ZipFile(zipFile)) {
        addTotalWork(zip.size());//w w w . jav a  2 s  .  c  o m
        Enumeration<? extends ZipEntry> entries = zip.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String escapedEntryName = escapeFileName(entry.getName());
            File entryFile = new File(baseDirectory, escapedEntryName);

            if (entry.isDirectory()) {
                if (!contains(entryFile.getAbsolutePath(), ignoredDirectories)) {
                    entryFile.mkdir();
                }
            } else if (!endsWith(entryFile.getName(), ignoredExtensions)
                    && !contains(entryFile.getAbsolutePath(), ignoredDirectories)) {
                if (entryFile.getAbsolutePath().indexOf(File.separatorChar,
                        baseDirectory.getAbsolutePath().length()) > -1) {
                    // Only create dirs if file is not in the root dir
                    entryFile.getParentFile().mkdirs();
                }

                try (InputStream is = zip.getInputStream(entry);
                        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(entryFile))) {
                    copyInputStream(is, outputStream);
                }

                if (extractContainedZipFiles && (escapedEntryName.toLowerCase().endsWith(".zip")
                        || escapedEntryName.toLowerCase().endsWith(".war"))) {
                    String zipFileName = escapedEntryName;
                    File zipFileBaseDir = new File(baseDirectory,
                            zipFileName.substring(0, zipFileName.length() - 4));
                    zipFileBaseDir.mkdir();

                    unzip(entryFile, zipFileBaseDir, false, exceptions);
                    entryFile.delete();
                } else if (extractContainedZipFiles && (escapedEntryName.toLowerCase().endsWith(".tar")
                        || escapedEntryName.toLowerCase().endsWith(".gz"))) {
                    String zipFileName = escapedEntryName;
                    int offset = escapedEntryName.toLowerCase().endsWith(".tar") ? 4 : 0;
                    offset = escapedEntryName.toLowerCase().endsWith(".tar.gz") ? 7 : offset;
                    File zipFileBaseDir = new File(baseDirectory,
                            zipFileName.substring(0, zipFileName.length() - offset));
                    zipFileBaseDir.mkdir();

                    untar(entryFile, zipFileBaseDir, exceptions,
                            escapedEntryName.toLowerCase().endsWith(".tar.gz"));
                    entryFile.delete();
                } else if (extractContainedZipFiles && escapedEntryName.toLowerCase().endsWith(".rar")) {
                    String zipFileName = escapedEntryName;
                    File zipFileBaseDir = new File(baseDirectory,
                            zipFileName.substring(0, zipFileName.length() - 4));
                    zipFileBaseDir.mkdir();

                    unrar(entryFile, zipFileBaseDir, exceptions);
                    entryFile.delete();
                }
            }

            addDoneWork(1);
        }
    } catch (Exception ex) {
        exceptions.add(ex);
    }
}

From source file:com.samczsun.helios.LoadedFile.java

public void reset() throws IOException {
    files.clear();/* w  w w  .  j av  a 2s  .  c o  m*/
    classes.clear();
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
        while (enumeration.hasMoreElements()) {
            ZipEntry zipEntry = enumeration.nextElement();
            if (!zipEntry.isDirectory()) {
                load(zipEntry.getName(), zipFile.getInputStream(zipEntry));
            }
        }
    } catch (ZipException e) { //Probably not a ZIP file
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            load(this.name, inputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:Zip.java

/**
 * Create a Reader on a given file, by looking for a zip archive whose path
 * is the file path with ".zip" appended, and by reading the first entry in
 * this zip file.// ww  w . ja  va  2 s  . com
 *
 * @param file the file (with no zip extension)
 *
 * @return a reader on the zip entry
 */
public static Reader createReader(File file) {
    try {
        String path = file.getCanonicalPath();

        ZipFile zf = new ZipFile(path + ".zip");

        for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            InputStream is = zf.getInputStream(entry);

            return new InputStreamReader(is);
        }
    } catch (FileNotFoundException ex) {
        System.err.println(ex.toString());
        System.err.println(file + " not found");
    } catch (IOException ex) {
        System.err.println(ex.toString());
    }

    return null;
}

From source file:net.sourceforge.jweb.maven.mojo.InWarMinifyMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled)
        return;/*from  w  w w  . j  av  a  2 s  .  c om*/
    processConfiguration();
    String name = this.getBuilddir().getAbsolutePath() + File.separator + this.getFinalName() + "."
            + this.getPacking();
    this.getLog().info(name);
    MinifyFileFilter fileFilter = new MinifyFileFilter();
    int counter = 0;
    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            //no compress, just transfer to war
            if (!fileFilter.accept(entry)) {
                getLog().debug("nocompress entry: " + entry.getName());
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }

            File sourceTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".tmp");
            File destTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".min.tmp");
            FileUtils.writeStringToFile(sourceTmp, "");
            FileUtils.writeStringToFile(destTmp, "");

            //assemble arguments
            String[] provied = getYuiArguments();
            int length = (provied == null ? 0 : provied.length);
            length += 5;
            int i = 0;

            String[] ret = new String[length];

            ret[i++] = "--type";
            ret[i++] = (entry.getName().toLowerCase().endsWith(".css") ? "css" : "js");

            if (provied != null) {
                for (String s : provied) {
                    ret[i++] = s;
                }
            }

            ret[i++] = sourceTmp.getAbsolutePath();
            ret[i++] = "-o";
            ret[i++] = destTmp.getAbsolutePath();

            try {
                InputStream in = zipFile.getInputStream(entry);
                FileUtils.copyInputStreamToFile(in, sourceTmp);
                in.close();

                YUICompressorNoExit.main(ret);
            } catch (Exception e) {
                this.getLog().warn("compress error, this file will not be compressed:" + buildStack(e));
                FileUtils.copyFile(sourceTmp, destTmp);
            }

            out.putNextEntry(new ZipEntry(entry.getName()));
            InputStream compressedIn = new FileInputStream(destTmp);
            byte[] buf = new byte[512];
            int len = -1;
            while ((len = compressedIn.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            compressedIn.close();

            String sourceSize = decimalFormat.format(sourceTmp.length() * 1.0d / 1024) + " KB";
            String destSize = decimalFormat.format(destTmp.length() * 1.0d / 1024) + " KB";
            getLog().info("compressed entry:" + entry.getName() + " [" + sourceSize + " ->" + destSize + "/"
                    + numberFormat.format(1 - destTmp.length() * 1.0d / sourceTmp.length()) + "]");

            counter++;
        }
        zipFile.close();
        out.close();

        FileUtils.cleanDirectory(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
        FileUtils.forceDelete(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.limegroup.gnutella.gui.LanguageUtils.java

/**
 * Returns the languages as found from the classpath in messages.jar
 *//* w w w. j  a v  a2 s. c o m*/
static void addLocalesFromJar(List<Locale> locales, File jar) {
    ZipFile zip = null;
    try {
        zip = new ZipFile(jar);
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (!name.startsWith(BUNDLE_PREFIX) || !name.endsWith(BUNDLE_POSTFIX) || name.indexOf("$") != -1) {
                continue;
            }

            String iso = name.substring(BUNDLE_PREFIX.length(), name.length() - BUNDLE_POSTFIX.length());
            List<String> tokens = new ArrayList<String>(Arrays.asList(iso.split("_", 3)));
            if (tokens.size() < 1) {
                continue;
            }
            while (tokens.size() < 3) {
                tokens.add("");
            }

            Locale locale = new Locale(tokens.get(0), tokens.get(1), tokens.get(2));
            locales.add(locale);
        }
    } catch (IOException e) {
        LOG.warn("Could not determine locales", e);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException ioe) {
            }
        }
    }
}