Example usage for java.util.zip ZipInputStream close

List of usage examples for java.util.zip ZipInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.denel.facepatrol.MainActivity.java

private void downloadunzip() throws IOException {
    // for now the file is from assets but will be downloaded later
    String PATH = getApplicationContext().getDir("pictures", 0).getAbsolutePath() + "/";
    InputStream is = getApplicationContext().getAssets().open("ContactsPics.zip");

    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    try {/*from  w  w w. ja  v  a2s  .c  om*/
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        while ((ze = zis.getNextEntry()) != null) {

            if (ze.isDirectory()) {
                _dirchecker((ze.getName()));
            } else {
                FileOutputStream baos = new FileOutputStream(PATH + ze.getName());
                BufferedInputStream in = new BufferedInputStream(zis);
                BufferedOutputStream out = new BufferedOutputStream(baos);

                int count;
                while ((count = in.read(buffer)) > 0) {
                    out.write(buffer, 0, count);
                }
                zis.closeEntry();
                out.close();
            }

        }
    } finally {
        zis.close();
    }
}

From source file:com.sastix.cms.server.services.content.impl.ZipFileHandlerServiceImpl.java

@Override
public DataMaps unzip(byte[] bytes) throws IOException {
    Map<String, String> foldersMap = new HashMap<>();

    Map<String, byte[]> extractedBytesMap = new HashMap<>();
    InputStream byteInputStream = new ByteArrayInputStream(bytes);
    //validate that it is a zip file
    if (isZipFile(bytes)) {
        try {//from   w  w  w  . java2  s  .  c o m
            //get the zip file content
            ZipInputStream zis = new ZipInputStream(byteInputStream);
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {
                String fileName = ze.getName();
                if (!ze.isDirectory()) {//if entry is a directory, we should not add it as a file
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        ByteBuffer bufIn = ByteBuffer.allocate(1024);
                        int bytesRead;
                        while ((bytesRead = zis.read(bufIn.array())) > 0) {
                            baos.write(bufIn.array(), 0, bytesRead);
                            bufIn.rewind();
                        }
                        bufIn.clear();
                        extractedBytesMap.put(fileName, baos.toByteArray());
                    } finally {
                        baos.close();
                    }
                } else {
                    foldersMap.put(fileName, fileName);
                }
                ze = zis.getNextEntry();
            }
            zis.closeEntry();
            zis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    DataMaps dataMaps = new DataMaps();
    dataMaps.setBytesMap(extractedBytesMap);
    dataMaps.setFoldersMap(foldersMap);
    return dataMaps;
}

From source file:com.joliciel.csvLearner.CSVLearner.java

private void doCommandAnalyse() throws IOException {
    if (featureDir == null)
        throw new RuntimeException("Missing argument: featureDir");
    if (maxentModelFilePath == null)
        throw new RuntimeException("Missing argument: maxentModel");
    if (outfilePath == null)
        throw new RuntimeException("Missing argument: outfile");

    CSVEventListReader reader = this.getReader(TrainingSetType.ALL_TEST, false);

    GenericEvents events = reader.getEvents();

    try {/*from w  ww  . j  ava 2s  .c o  m*/
        LOG.info("Evaluating test events...");
        ZipInputStream zis = new ZipInputStream(new FileInputStream(maxentModelFilePath));
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            if (ze.getName().endsWith(".bin"))
                break;
        }
        MaxentModel model = new MaxentModelReader(zis).getModel();
        zis.close();

        MaxentAnalyser analyser = new MaxentAnalyser();
        analyser.setMaxentModel(model);
        if (preferredOutcome != null) {
            analyser.setPreferredOutcome(preferredOutcome);
            analyser.setBias(bias);
        }

        if (outfilePath.lastIndexOf('/') >= 0) {
            String outDirPath = outfilePath.substring(0, outfilePath.lastIndexOf('/'));

            File outDir = new File(outDirPath);
            outDir.mkdirs();
        }

        File outcomeFile = new File(outfilePath);

        if (outfilePath.endsWith(".xml")) {
            MaxentOutcomeXmlWriter xmlWriter = new MaxentOutcomeXmlWriter(outcomeFile);
            xmlWriter.setMinProbToConsider(minProbToConsider);
            xmlWriter.setUnknownOutcomeName(unknownOutcomeName);
            analyser.addObserver(xmlWriter);
        } else {
            MaxentOutcomeCsvWriter csvWriter = new MaxentOutcomeCsvWriter(model, outcomeFile);
            csvWriter.setMinProbToConsider(minProbToConsider);
            csvWriter.setUnknownOutcomeName(unknownOutcomeName);
            analyser.addObserver(csvWriter);
        }

        MaxentBestFeatureObserver bestFeatureObserver = null;
        if (!crossValidation && featureCount > 0 && resultFilePath != null) {
            bestFeatureObserver = new MaxentBestFeatureObserver(model, featureCount,
                    reader.getFeatureToFileMap());
            analyser.addObserver(bestFeatureObserver);
        }

        MaxentFScoreCalculator maxentFScoreCalculator = null;
        if (resultFilePath != null) {
            maxentFScoreCalculator = new MaxentFScoreCalculator();
            maxentFScoreCalculator.setMinProbToConsider(minProbToConsider);
            maxentFScoreCalculator.setUnknownOutcomeName(unknownOutcomeName);
            analyser.addObserver(maxentFScoreCalculator);
        }

        analyser.analyse(events);

        if (maxentFScoreCalculator != null) {
            FScoreCalculator<String> fscoreCalculator = maxentFScoreCalculator.getFscoreCalculator();

            LOG.info("F-score: " + fscoreCalculator.getTotalFScore());

            File fscoreFile = new File(outfilePath + ".fscores.csv");
            fscoreCalculator.writeScoresToCSVFile(fscoreFile);
        }

        if (bestFeatureObserver != null) {
            File weightPerFileFile = new File(outfilePath + ".weightPerFile.csv");
            weightPerFileFile.delete();
            weightPerFileFile.createNewFile();
            Writer weightPerFileWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(weightPerFileFile, false), "UTF8"));
            try {
                bestFeatureObserver.writeFileTotalsToFile(weightPerFileWriter);
            } finally {
                weightPerFileWriter.flush();
                weightPerFileWriter.close();
            }

            LOG.debug("Total feature count: " + reader.getFeatures().size());
        }
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }

    if (generateEventFile) {
        File eventFile = new File(outfilePath + ".events.txt");
        this.generateEventFile(eventFile, events);
    }
    LOG.info("#### Complete ####");
}

From source file:org.eclipse.dirigible.repository.zip.ZipImporter.java

/**
 * Import all the content from a given zip to the target repository instance
 * within the given path, overrides files during the pass and removes the root folder name
 *
 * @param repository/* w  w  w  .j a  v a 2  s . com*/
 * @param zipInputStream
 * @param relativeRoot
 * @param override
 * @param excludeRootFolderName
 * @param filter
 *            map of old/new string for replacement in paths
 * @throws IOException
 */
public static void importZip(IRepository repository, ZipInputStream zipInputStream, String relativeRoot,
        boolean override, boolean excludeRootFolderName, Map<String, String> filter) throws IOException {
    try {
        ZipEntry entry;
        String parentFolder = null;
        while ((entry = zipInputStream.getNextEntry()) != null) {

            if (excludeRootFolderName && (parentFolder == null)) {
                parentFolder = entry.getName();
                continue;
            }

            String entryName = getEntryName(entry, parentFolder, excludeRootFolderName);

            String outpath = relativeRoot + IRepository.SEPARATOR + entryName;

            if (filter != null) {
                for (Map.Entry<String, String> forReplacement : filter.entrySet()) {
                    outpath = outpath.replace(forReplacement.getKey(), forReplacement.getValue());
                }
            }

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                IOUtils.copy(zipInputStream, output);
                try {
                    if (output.toByteArray().length > 0) {
                        // TODO filter for binary extensions
                        String mimeType = null;
                        String extension = ContentTypeHelper.getExtension(entry.getName());
                        if ((mimeType = ContentTypeHelper.getContentType(extension)) != null) {
                            repository.createResource(outpath, output.toByteArray(),
                                    ContentTypeHelper.isBinary(mimeType), mimeType, override);
                        } else {
                            repository.createResource(outpath, output.toByteArray());
                        }
                    } else {
                        if (outpath.endsWith("/")) {
                            repository.createCollection(outpath);
                        }
                    }
                } catch (Exception e) {
                    logger.error(String.format("Error importing %s", outpath), e);
                }
            } finally {
                output.close();
            }
        }
    } finally {
        zipInputStream.close();
    }

}

From source file:com.amazonaws.eclipse.dynamodb.testtool.TestToolManager.java

/**
 * Unzip the given file into the given directory.
 *
 * @param zipFile The zip file to unzip.
 * @param unzipped The directory to put the unzipped files into.
 * @throws IOException on file system error.
 *//*from ww w  . j a va2 s  .c  om*/
private void unzip(final File zipFile, final File unzipped) throws IOException {

    ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile));
    try {

        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null) {
            Path path = new Path(entry.getName());

            File dest = new File(unzipped, path.toOSString());
            if (entry.isDirectory()) {
                if (!dest.mkdirs()) {
                    throw new RuntimeException("Failed to create directory while unzipping");
                }
            } else {
                FileOutputStream output = new FileOutputStream(dest);
                try {
                    IOUtils.copy(zip, output);
                } finally {
                    output.close();
                }
            }
        }

    } finally {
        zip.close();
    }
}

From source file:gov.nasa.ensemble.resources.ResourceUtil.java

public static IProject unzipProject(String projectName, ZipInputStream zis, IProgressMonitor monitor)
        throws CoreException, IOException {
    final String dirPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getAbsolutePath();
    if (monitor == null)
        monitor = new NullProgressMonitor();
    try {/*from   w  w  w . j a v a 2s.  c  o m*/
        monitor.beginTask("Loading " + projectName, 300);
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            File to = (!new File(dirPath, entry.getName()).getAbsolutePath().contains(projectName))
                    ? new File(dirPath + File.separator + projectName, entry.getName())
                    : new File(dirPath, entry.getName());
            if (entry.isDirectory()) {
                if (!to.exists() && !to.mkdirs()) {
                    throw new IOException("Error creating directory: " + to);
                }
            } else {
                File parent = to.getParentFile();
                if (parent != null && !parent.exists() && !parent.mkdirs()) {
                    throw new IOException("Error creating directory: " + parent);
                }
                FileOutputStream fos = new FileOutputStream(to);
                try {
                    monitor.subTask("Expanding: " + to.getName());
                    IOUtils.copy(zis, fos);
                } finally {
                    IOUtils.closeQuietly(fos);
                }
            }
            monitor.worked(10);
        }
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
        project.create(null);
        project.open(null);
        return project;
    } catch (IOException e) {
        throw new CoreException(
                new ExceptionStatus(EnsembleResourcesPlugin.PLUGIN_ID, "adding project to workspace", e));
    } finally {
        zis.close();
        monitor.done();
    }
}

From source file:net.pms.configuration.DownloadPlugins.java

private void unzip(File f, String dir) {
    // Zip file with loads of goodies
    // Unzip it/*from  w  ww.  j av  a 2s .  co  m*/
    ZipInputStream zis;
    try {
        zis = new ZipInputStream(new FileInputStream(f));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            File dst = new File(dir + File.separator + entry.getName());
            if (entry.isDirectory()) {
                dst.mkdirs();
                continue;
            }
            int count;
            byte data[] = new byte[4096];
            FileOutputStream fos = new FileOutputStream(dst);
            try (BufferedOutputStream dest = new BufferedOutputStream(fos, 4096)) {
                while ((count = zis.read(data, 0, 4096)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
            }
            if (dst.getAbsolutePath().endsWith(".jar")) {
                jars.add(dst.toURI().toURL());
            }
        }
        zis.close();
    } catch (Exception e) {
        LOGGER.info("unzip error " + e);
    }
    f.delete();
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java

public void unZip(String zipFile, String outputFolder) {
    byte[] buffer = new byte[1024];

    try {/*  www . j  ava  2 s  .c o  m*/
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));

        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);

            log.info("file unzip : " + newFile.getAbsoluteFile());

            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            fos.close();
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:net.ymate.platform.core.beans.impl.DefaultBeanLoader.java

private List<Class<?>> __doFindClassByZip(URL zipUrl, IBeanFilter filter) throws Exception {
    List<Class<?>> _returnValue = new ArrayList<Class<?>>();
    ZipInputStream _zipStream = null;
    try {/*from w  w w  .  j a va  2 s.  c  o  m*/
        String _zipFilePath = zipUrl.toString();
        if (_zipFilePath.indexOf('!') > 0) {
            _zipFilePath = StringUtils.substringBetween(zipUrl.toString(), "zip:", "!");
        } else {
            _zipFilePath = StringUtils.substringAfter(zipUrl.toString(), "zip:");
        }
        File _zipFile = new File(_zipFilePath);
        if (!__doCheckExculedFile(_zipFile.getName())) {
            _zipStream = new ZipInputStream(new FileInputStream(_zipFile));
            ZipEntry _zipEntry = null;
            while (null != (_zipEntry = _zipStream.getNextEntry())) {
                if (!_zipEntry.isDirectory()) {
                    if (_zipEntry.getName().endsWith(".class") && _zipEntry.getName().indexOf('$') < 0) {
                        String _className = StringUtils.substringBefore(_zipEntry.getName().replace("/", "."),
                                ".class");
                        __doAddClass(_returnValue, __doLoadClass(_className), filter);
                    }
                }
                _zipStream.closeEntry();
            }
        }
    } finally {
        if (_zipStream != null) {
            try {
                _zipStream.close();
            } catch (IOException ignored) {
            }
        }
    }
    return _returnValue;
}