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:apim.restful.exportimport.utils.APIImportUtil.java

/**
 * This method decompresses the archive/*from  www .  ja  v  a  2s. c o m*/
 *
 * @param sourceFile           the archive containing the API
 * @param destinationDirectory location of the archive to be extracted
 * @return extractedFolder the name of the zip
 */
public static String unzipArchive(File sourceFile, File destinationDirectory) throws APIManagementException {

    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    File destinationFile;
    ZipFile zipfile = null;
    String extractedFolder = null;

    try {
        zipfile = new ZipFile(sourceFile);
        Enumeration zipEntries = null;
        if (zipfile != null) {
            zipEntries = zipfile.entries();
        }
        if (zipEntries != null) {
            int index = 0;
            while (zipEntries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) zipEntries.nextElement();

                if (entry.isDirectory()) {

                    //This index variable is used to get the extracted folder name; that is root directory
                    if (index == 0) {

                        //Get the folder name without the '/' character at the end
                        extractedFolder = entry.getName().substring(0, entry.getName().length() - 1);
                    }
                    index = -1;
                    new File(destinationDirectory, entry.getName()).mkdir();
                    continue;
                }
                inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
                destinationFile = new File(destinationDirectory, entry.getName());
                fileOutputStream = new FileOutputStream(destinationFile);
                copyStreams(inputStream, fileOutputStream);
            }
        }
    } catch (ZipException e) {
        log.error("Error in retrieving archive files.");
        throw new APIManagementException("Error in retrieving archive files.", e);
    } catch (IOException e) {
        log.error("Error in decompressing API archive files.");
        throw new APIManagementException("Error in decompressing API archive files.", e);
    } finally {
        try {
            if (zipfile != null) {
                zipfile.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        } catch (IOException e) {
            log.error("Error in closing streams while decompressing files.");
        }
    }
    return extractedFolder;
}

From source file:com.alibaba.otter.shared.common.utils.extension.classpath.FileSystemClassScanner.java

private Class<?> scanInJar(String jarFileName, String className) {
    ZipFile zipfile = null;//  w  w w .ja  v a  2s . co  m

    try {
        zipfile = new ZipFile(jarFileName);
        Enumeration<?> zipenum = zipfile.entries();
        ZipEntry entry = null;
        String tempClassName = null;

        while (zipenum.hasMoreElements()) {
            entry = (ZipEntry) zipenum.nextElement();
            tempClassName = entry.getName();

            if (tempClassName.endsWith(".class")) {
                tempClassName = StringUtils.replace(FilenameUtils.removeExtension(tempClassName), "/", ".");
                if (tempClassName.equals(className)) {
                    try {
                        return fileClassLoader.loadClass(className);
                    } catch (Exception ex) {
                        logger.warn("WARN ## load this class has an error,the fileName is = " + className, ex);
                    }
                }
            }
        }
    } catch (IOException ex) {
        logger.error(ex.getMessage(), ex);
    } finally {
        if (zipfile != null) {
            try {
                zipfile.close();
            } catch (IOException ex) {
                logger.warn(ex.getMessage(), ex);
            }
        }
    }
    return null;
}

From source file:io.frictionlessdata.datapackage.Package.java

/**
 * Load from String representation of JSON object or from a zip file path.
 * @param jsonStringSource/* w w  w .jav a 2 s .c  o m*/
 * @param strict
 * @throws IOException
 * @throws DataPackageException
 * @throws ValidationException
 */
public Package(String jsonStringSource, boolean strict)
        throws IOException, DataPackageException, ValidationException {
    this.strictValidation = strict;

    // If zip file is given.
    if (jsonStringSource.toLowerCase().endsWith(".zip")) {
        // Read in memory the file inside the zip.
        ZipFile zipFile = new ZipFile(jsonStringSource);
        ZipEntry entry = zipFile.getEntry(DATAPACKAGE_FILENAME);

        // Throw exception if expected datapackage.json file not found.
        if (entry == null) {
            throw new DataPackageException(
                    "The zip file does not contain the expected file: " + DATAPACKAGE_FILENAME);
        }

        // Read the datapackage.json file inside the zip
        try (InputStream is = zipFile.getInputStream(entry)) {
            StringBuilder out = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    out.append(line);
                }
            }

            // Create and set the JSONObject for the datapackage.json that was read from inside the zip file.
            this.setJson(new JSONObject(out.toString()));

            // Validate.
            this.validate();
        }

    } else {
        // Create and set the JSONObject fpr the String representation of desriptor JSON object.
        this.setJson(new JSONObject(jsonStringSource));

        // If String representation of desriptor JSON object is provided.
        this.validate();
    }
}

From source file:asciidoc.maven.plugin.AbstractAsciiDocMojo.java

private void unzipArchive(File archive, File outputDir) {
    try {/*from ww w .j a  va 2 s  .co  m*/
        ZipFile zipfile = new ZipFile(archive);
        for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            unzipEntry(zipfile, entry, outputDir);
        }
    } catch (Exception e) {
        getLog().error("Error while extracting file " + archive, e);
    }
}

From source file:com.icesoft.icefaces.tutorial.component.autocomplete.AutoCompleteDictionary.java

private static void init() {
    // Raw list of xml cities.
    List cityList = null;//from  ww  w  .  ja v  a  2 s .c om

    // load the city dictionary from the compressed xml file.

    // get the path of the compressed file
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    String basePath = session.getServletContext().getRealPath("/WEB-INF/resources");
    basePath += "/city.xml.zip";

    // extract the file
    ZipEntry zipEntry;
    ZipFile zipFile;
    try {
        zipFile = new ZipFile(basePath);
        zipEntry = zipFile.getEntry("city.xml");
    } catch (Exception e) {
        log.error("Error retrieving records", e);
        return;
    }

    // get the xml stream and decode it.
    if (zipFile.size() > 0 && zipEntry != null) {
        try {
            BufferedInputStream dictionaryStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));
            XMLDecoder xDecoder = new XMLDecoder(dictionaryStream);
            // get the city list.
            cityList = (List) xDecoder.readObject();
            dictionaryStream.close();
            zipFile.close();
            xDecoder.close();
        } catch (ArrayIndexOutOfBoundsException e) {
            log.error("Error getting city list, not city objects", e);
            return;
        } catch (IOException e) {
            log.error("Error getting city list", e);
            return;
        }
    }

    // Finally load the object from the xml file.
    if (cityList != null) {
        dictionary = new ArrayList(cityList.size());
        City tmpCity;
        for (int i = 0, max = cityList.size(); i < max; i++) {
            tmpCity = (City) cityList.get(i);
            if (tmpCity != null && tmpCity.getCity() != null) {
                dictionary.add(new SelectItem(tmpCity, tmpCity.getCity()));
            }
        }
        cityList.clear();
        // finally sort the list
        Collections.sort(dictionary, LABEL_COMPARATOR);
    }

}

From source file:com.sshtools.j2ssh.util.ExtensionClassLoader.java

public boolean isJarArchive(File file) {
    boolean isArchive = true;
    ZipFile zipFile = null;//  ww w .j  av a  2s.  c om

    try {
        zipFile = new ZipFile(file);
    } catch (ZipException zipCurrupted) {
        isArchive = false;
    } catch (IOException anyIOError) {
        isArchive = false;
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ignored) {
            }
        }
    }

    return isArchive;
}

From source file:de.xwic.appkit.core.util.ZipUtil.java

/**
 * Unzips the files from the zipped file into the destination folder.
 * //ww w  . j a va  2 s  . c om
 * @param zippedFile
 *            the files array
 * @param destinationFolder
 *            the folder in which the zip archive will be unzipped
 * @return the file array which consists into the files which were zipped in
 *         the zippedFile
 * @throws IOException
 */
public static File[] unzip(File zippedFile, String destinationFolder) throws IOException {

    ZipFile zipFile = null;
    List<File> files = new ArrayList<File>();

    try {

        zipFile = new ZipFile(zippedFile);
        Enumeration<?> entries = zipFile.entries();

        while (entries.hasMoreElements()) {

            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (!entry.isDirectory()) {

                String filePath = destinationFolder + System.getProperty("file.separator") + entry.getName();
                FileOutputStream stream = new FileOutputStream(filePath);

                InputStream is = zipFile.getInputStream(entry);

                log.info("Unzipping " + entry.getName());

                int n = 0;
                while ((n = is.read(BUFFER)) > 0) {
                    stream.write(BUFFER, 0, n);
                }

                is.close();
                stream.close();

                files.add(new File(filePath));

            }

        }

        zipFile.close();
    } catch (IOException e) {

        log.error("Error: " + e.getMessage(), e);
        throw e;

    } finally {

        try {

            if (null != zipFile) {
                zipFile.close();
            }

        } catch (IOException e) {
            log.error("Error: " + e.getMessage(), e);
            throw e;
        }

    }

    File[] array = files.toArray(new File[files.size()]);
    return array;
}

From source file:de.lmu.ifi.dbs.jfeaturelib.utils.PackageScanner.java

List<String> getNames(Package inPackage)
        throws UnsupportedEncodingException, URISyntaxException, ZipException, IOException {
    List<String> binaryNames = new ArrayList<>();

    String packagePath = inPackage.getName();
    packagePath = packagePath.replace('.', '/');

    // During tests, this points to the classes/ directory, later, this points to the jar
    CodeSource src = PackageScanner.class.getProtectionDomain().getCodeSource();
    URL location = src.getLocation();
    // test case/*from  w ww  .j  a  va 2 s  .c om*/
    File dirOrJar = new File(location.toURI());
    if (dirOrJar.isDirectory()) {
        // +1 to include the slash after the directory name
        int basePathLength = dirOrJar.toString().length() + 1;
        File packageDir = new File(dirOrJar, packagePath);

        // list all .class files in this package directory
        for (File file : packageDir.listFiles((FilenameFilter) new SuffixFileFilter(".class"))) {
            // strip the leading directory
            String binaryName = file.getPath().substring(basePathLength);
            binaryName = pathToBinary(binaryName);
            binaryNames.add(binaryName);
        }

    } else {
        try (ZipFile jar = new ZipFile(dirOrJar)) {
            for (Enumeration entries = jar.entries(); entries.hasMoreElements();) {
                String binaryName = ((ZipEntry) entries.nextElement()).getName();
                if (!binaryName.endsWith(".class")) { // we only need classes
                    continue;
                }
                if (binaryName.startsWith(packagePath)) {
                    binaryName = pathToBinary(binaryName);
                    binaryNames.add(binaryName);
                }
            }
        }
    }

    return binaryNames;
}

From source file:android.databinding.tool.util.GenerationalClassUtil.java

private static void loadFomZipFile(File file) throws IOException {
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        for (ExtensionFilter filter : ExtensionFilter.values()) {
            if (!filter.accept(entry.getName())) {
                continue;
            }/* w  w w. j  av a 2s. c om*/
            InputStream inputStream = null;
            try {
                inputStream = zipFile.getInputStream(entry);
                Serializable item = fromInputStream(inputStream);
                L.d("loaded item %s from zip file", item);
                if (item != null) {
                    //noinspection unchecked
                    sCache[filter.ordinal()].add(item);
                }
            } catch (IOException e) {
                L.e(e, "Could not merge in Bindables from %s", file.getAbsolutePath());
            } catch (ClassNotFoundException e) {
                L.e(e, "Could not read Binding properties intermediate file. %s", file.getAbsolutePath());
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }
}

From source file:gui.accessories.DownloadProgressWork.java

/**
 * Uncompress all the files contained in the compressed file and its folders in the same folder where the zip file is placed. Doesn't respects the
 * directory tree of the zip file. This method seems a clear candidate to ZipManager.
 *
 * @param file Zip file.//  w ww .j  a  v  a2 s.  co  m
 * @return Count of files uncopressed.
 * @throws ZipException Exception.
 */
private int doUncompressZip(File file) throws ZipException {
    int fileCount = 0;
    try {
        byte[] buf = new byte[1024];
        ZipFile zipFile = new ZipFile(file);

        Enumeration zipFileEntries = zipFile.entries();

        while (zipFileEntries.hasMoreElements()) {
            ZipEntry zipentry = (ZipEntry) zipFileEntries.nextElement();
            if (zipentry.isDirectory()) {
                continue;
            }
            File entryZipFile = new File(zipentry.getName());
            File outputFile = new File(file.getParentFile(), entryZipFile.getName());
            FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
            InputStream is = zipFile.getInputStream(zipentry);
            int n;
            while ((n = is.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }
            fileoutputstream.close();
            is.close();
            fileoutputstream.close();
            fileCount++;
        }
        zipFile.close();

    } catch (IOException ex) {
        throw new ZipException(ex.getMessage());
    }

    return fileCount;
}