Example usage for java.util.zip ZipFile getInputStream

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

Introduction

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

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:net.rptools.lib.FileUtil.java

public static void unzipFile(File sourceFile, File destDir) throws IOException {
    if (!sourceFile.exists())
        throw new IOException("source file does not exist: " + sourceFile);

    ZipFile zipFile = null;
    InputStream is = null;/*from w ww  .j  a  v  a 2 s . co  m*/
    OutputStream os = null;
    try {
        zipFile = new ZipFile(sourceFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory())
                continue;

            File file = new File(destDir, entry.getName());
            String path = file.getAbsolutePath();
            file.getParentFile().mkdirs();

            //System.out.println("Writing file: " + path);
            is = zipFile.getInputStream(entry);
            os = new BufferedOutputStream(new FileOutputStream(path));
            copyWithClose(is, os);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        try {
            if (zipFile != null)
                zipFile.close();
        } catch (Exception e) {
        }
    }
}

From source file:nz.ac.otago.psyanlab.common.util.FileUtils.java

/**
 * Inflate a pale file to a given working directory.
 * /*from  www .java 2 s  . c o  m*/
 * @param paleFile .pale file to inflate.
 * @param workingDir Path to extract to.
 * @return Path of the location the file was extracted to.
 * @throws FileNotFoundException
 * @throws IOException
 */
public static File decompress(File paleFile, File workingDir) throws FileNotFoundException, IOException {
    ZipFile archive = new ZipFile(paleFile);

    try {
        // Iterate over elements in zip file and extract them to working
        // directory.
        Enumeration<? extends ZipEntry> entries = archive.entries();
        while (entries.hasMoreElements()) {
            ZipEntry ze = entries.nextElement();
            File newFile = new File(workingDir, ze.getName());

            if (ze.isDirectory()) {
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                continue;
            }

            if (!newFile.getParentFile().exists()) {
                // Dir tree missing for some reason so create it.
                newFile.getParentFile().mkdirs();
            }

            InputStream in = archive.getInputStream(ze);
            OutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));

            try {
                copy(in, out);
            } finally {
                in.close();
                out.close();
            }
        }
    } finally {
        archive.close();
    }

    return workingDir;
}

From source file:org.agnitas.util.ZipUtilities.java

/**
 * Open an existing Zip file for adding new entries.
 * All existing entries in the zipped file will be copied in the new one.
 * //from   w  w  w.ja v a  2s  . c o m
 * @param zipFile
 * @return
 * @throws IOException 
 * @throws ZipException 
 */
public static ZipOutputStream openExistingZipFileForExtension(File zipFile) throws IOException {
    // Rename source Zip file (Attention: the String path and name of the zipFile are preserved
    File originalFileTemp = new File(
            zipFile.getParentFile().getAbsolutePath() + "/" + String.valueOf(System.currentTimeMillis()));
    zipFile.renameTo(originalFileTemp);

    ZipFile sourceZipFile = new ZipFile(originalFileTemp);
    ZipOutputStream zipOutputStream = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(zipFile)));

    BufferedInputStream bufferedInputStream = null;

    try {
        // copy entries
        Enumeration<? extends ZipEntry> srcEntries = sourceZipFile.entries();
        while (srcEntries.hasMoreElements()) {
            ZipEntry sourceZipFileEntry = srcEntries.nextElement();
            zipOutputStream.putNextEntry(sourceZipFileEntry);

            bufferedInputStream = new BufferedInputStream(sourceZipFile.getInputStream(sourceZipFileEntry));

            byte[] bufferArray = new byte[1024];
            int byteBufferFillLength = bufferedInputStream.read(bufferArray);
            while (byteBufferFillLength > -1) {
                zipOutputStream.write(bufferArray, 0, byteBufferFillLength);
                byteBufferFillLength = bufferedInputStream.read(bufferArray);
            }

            zipOutputStream.closeEntry();

            bufferedInputStream.close();
            bufferedInputStream = null;
        }

        zipOutputStream.flush();
        sourceZipFile.close();
        originalFileTemp.delete();

        return zipOutputStream;
    } catch (IOException e) {
        // delete existing Zip file
        if (zipFile.exists()) {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (Exception ex) {
                }
                zipOutputStream = null;
            }
            zipFile.delete();
        }

        // revert renaming of source Zip file
        originalFileTemp.renameTo(zipFile);
        throw e;
    } finally {
        if (bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (Exception e) {
            }
            bufferedInputStream = null;
        }
    }
}

From source file:lucee.commons.io.compress.CompressUtil.java

private static void unzip2(File zipFile, Resource targetDir) throws IOException {
    ZipFile zf = null;
    try {/*from   w  ww. j a v a 2 s  . c o m*/
        zf = new ZipFile(zipFile);

        ZipEntry entry;
        Enumeration en = zf.entries();
        while (en.hasMoreElements()) {
            entry = (ZipEntry) en.nextElement();
            Resource target = targetDir.getRealResource(entry.getName());
            if (entry.isDirectory()) {
                target.mkdirs();
            } else {
                Resource parent = target.getParentResource();
                if (!parent.exists())
                    parent.mkdirs();
                InputStream is = zf.getInputStream(entry);
                IOUtil.copy(is, target, true);
            }
            target.setLastModified(entry.getTime());
        }
    } finally {
        IOUtil.closeEL(zf);
    }
}

From source file:example.csv.PostalReader.java

@Override
public void open(Serializable checkpoint) throws Exception {
    ZipFile zipFile = new ZipFile(ZIP_PATH.toFile());
    ZipEntry csvEntry = zipFile.getEntry("42NAGASA.CSV");
    InputStreamReader reader = new InputStreamReader(zipFile.getInputStream(csvEntry),
            Charset.forName("Windows-31J"));
    parser = CSVFormat.RFC4180.withHeader(HEADER).parse(reader);
    csvIter = parser.iterator();//from   w  w  w .j av  a  2  s .c om
}

From source file:com.fluidops.iwb.luxid.LuxidExtractor.java

/**
 * extracts a zip-file and returns references to the unziped files. If the file passed to this method
 * is not a zip-file, a reference to the file is returned.
 * // ww w .  j  av a 2 s .c  om
 * @param fileName
 * @return
 * @throws Exception
 */
public static Set<File> extractZip(String fileName) throws Exception {
    File zipf = new File((new StringBuilder("luxid/")).append(fileName).toString());

    Set<File> toBeUploaded = new HashSet<File>();
    if (zipf.getName().endsWith(".zip")) {
        ZipFile zip = new ZipFile(zipf);
        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                logger.info((new StringBuilder("Extracting directory: ")).append(entry.getName()).toString());
                GenUtil.mkdir(new File(entry.getName()));
            } else {
                logger.info((new StringBuilder("Extracting file: ")).append(entry.getName()).toString());
                String entryPath = "luxid/" + entry.getName();
                FileOutputStream fileOutputStream = null;
                InputStream zipEntryStream = zip.getInputStream(entry);
                try {
                    fileOutputStream = new FileOutputStream(entryPath);
                    IOUtils.copy(zipEntryStream, fileOutputStream);
                } finally {
                    closeQuietly(zipEntryStream);
                    closeQuietly(fileOutputStream);
                }
                toBeUploaded.add(new File(entryPath));
            }
        }

        zip.close();
    } else {
        toBeUploaded.add(zipf);
    }

    return toBeUploaded;
}

From source file:org.atombeat.xquery.functions.util.StreamZipEntryToResponse.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    ResponseModule resModule = (ResponseModule) context.getModule(ResponseModule.NAMESPACE_URI);

    // request object is read from global variable $response
    Variable respVar = resModule.resolveVariable(ResponseModule.RESPONSE_VAR);

    if (respVar == null || respVar.getValue() == null)
        throw new XPathException(this, "No request object found in the current XQuery context.");

    if (respVar.getValue().getItemType() != Type.JAVA_OBJECT)
        throw new XPathException(this, "Variable $response is not bound to an Java object.");

    JavaObjectValue respValue = (JavaObjectValue) respVar.getValue().itemAt(0);

    if (!"org.exist.http.servlets.HttpResponseWrapper".equals(respValue.getObject().getClass().getName()))
        throw new XPathException(this,
                signature.toString() + " can only be used within the EXistServlet or XQueryServlet");

    ResponseWrapper response = (ResponseWrapper) respValue.getObject();

    String path = args[0].getStringValue();
    logger.debug(path);//from   www .j  a v a2 s  . co  m
    String entry = args[1].getStringValue();
    logger.debug(entry);
    String contentType = args[2].getStringValue();
    logger.debug(contentType);
    response.setContentType(contentType);

    try {

        ZipFile f = new ZipFile(path);
        ZipEntry e = f.getEntry(entry);
        InputStream in = f.getInputStream(e);
        OutputStream out = response.getOutputStream();
        Stream.copy(in, out);
        response.flushBuffer(); // is this necessary?

    } catch (Exception e) {
        e.printStackTrace();
        throw new XPathException(this, "Exception while streaming data from zip file: " + e.getMessage(), e);
    }

    return Sequence.EMPTY_SEQUENCE;
}

From source file:org.commonjava.indy.folo.ftest.content.admin.DownloadFromTrackedAndRetrieveInRepoZipTest.java

@Test
public void run() throws Exception {
    final String trackingId = newName();
    String path = "org/commonjava/commonjava/2/commonjava-2.pom";
    centralServer.expect(centralServer.formatUrl(path), 200, Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("folo-content/commonjava-2.pom"));

    InputStream result = client.module(IndyFoloContentClientModule.class).get(trackingId, remote, CENTRAL,
            path);/*from   ww  w.  j av  a  2 s  . c om*/
    assertThat(result, notNullValue());

    final String pom = IOUtils.toString(result);
    result.close();
    assertThat(pom.contains("<groupId>org.commonjava</groupId>"), equalTo(true));

    IndyFoloAdminClientModule module = client.module(IndyFoloAdminClientModule.class);
    boolean success = module.sealTrackingRecord(trackingId);
    assertThat(success, equalTo(true));

    result = module.getTrackingRepoZip(trackingId);

    assertThat(result, notNullValue());

    // ZipInputStream wrapping this resulting InputStream didn't seem to work...I was probably doing something wrong
    File f = getTemp().newFile("downloaded.zip");
    try (FileOutputStream fos = new FileOutputStream(f)) {
        IOUtils.copy(result, fos);
    }

    ZipFile zf = new ZipFile(f);
    ZipEntry entry = zf.getEntry(path);
    assertThat(entry, notNullValue());

    try (InputStream stream = zf.getInputStream(entry)) {
        String fromZip = IOUtils.toString(stream);
        assertThat("zip contents differ from direct download!", fromZip, equalTo(pom));
    }
}

From source file:de.psdev.energylogger.parser.EnergyLoggerDataParserImpl.java

List<LogEntry> handleZipEntry(final ZipFile zipFile, final ZipEntry zipEntry) {
    try {/*w  w w  .  j a  va2s.  c  o m*/
        return parseFileContents(zipFile.getInputStream(zipEntry));
    } catch (Exception e) {
        LOG.error(
                String.format("Error parsing zipEntry %s", (zipEntry != null) ? zipEntry.getName() : zipEntry),
                e);
    }
    return Collections.emptyList();
}

From source file:com.sshtools.j2ssh.authentication.UserGridCredential.java

private static void checkCACertificates(CoGProperties cogproperties) throws IOException {
    // check the directories exist and create if they don't
    String globusDir = System.getProperty("user.home") + "/.globus";
    if (!(new File(globusDir).exists())) {
        boolean success = (new File(globusDir).mkdir());
        if (!success) {
            throw new IOException("Couldn't create directory: " + globusDir);
        }/*from ww w . ja  v  a 2  s .  c o m*/
    }
    String caCertLocations = globusDir + "/certificates";
    File caCertLocationsF = new File(caCertLocations);
    if (!caCertLocationsF.exists()) {
        boolean success = (new File(caCertLocations).mkdir());
        if (!success) {
            throw new IOException("Couldn't create directory: " + caCertLocations);
        }
    }
    if (!caCertLocationsF.isDirectory()) {
        throw new IOException("Location: " + caCertLocations + " is not a directory");
    }
    File tmp = null;
    try {
        // save the zipfile temporarily
        tmp = File.createTempFile("certificates", ".zip");
        copyFile(thisDummy.getClass().getResourceAsStream("certificates.zip"), new FileOutputStream(tmp));
        ZipFile zf = new ZipFile(tmp);
        try {
            Enumeration e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze = (ZipEntry) e.nextElement();
                String name = ze.getName();
                if (!(new File(caCertLocations + File.separator + name).exists())) {
                    copyFile(zf.getInputStream(ze),
                            new FileOutputStream(new File(caCertLocations + File.separator + name)));
                }
            }
        } finally {
            if (zf != null)
                zf.close();
        }
    } catch (IOException e) {
        throw new IOException("Couldn't load certificates... " + e);
    } finally {
        // delete temp file
        if (tmp != null) {
            if (tmp.exists())
                tmp.delete();
        }
    }
}