Example usage for java.util.zip ZipFile getEntry

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

Introduction

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

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the zip file entry for the specified name, or null if not found.

Usage

From source file:com.idocbox.common.file.ZipExtracter.java

/**
 * extract given entry in zip file to destination directory.
 * if given entry is a directory, extract all folder and files under it to
 * destination directory.//from   www . j a v  a  2  s  .c  o  m
 * @param zipFileName  name of zip file.
 * @param entry   it can be a directory or a file.(if it is end with "/",it 
 *                will be treated as a directory.) . For example, 
 *                conf/ represents subdirectory in zip file.
 *                Use "/" to represent root of zip file.
  *                
 * @param desDir  destination directory.
 * @param startDirLevel the level to start create directory.
 *                      Its value is 1,2,...
 * @throws IOException 
 * @throws ZipException 
 */
public static void extract(final String zipFileName, final String entry, final String desDir,
        final int... startDirLevel) throws ZipException, IOException {
    File f = new File(zipFileName);
    if (f.exists()) {
        //check destination directory.
        File desf = new File(desDir);
        if (!desf.exists()) {
            desf.mkdirs();
        }

        boolean toExtractDir = false;
        if (entry.endsWith("/")) {
            toExtractDir = true;
        }

        //create zip file object.
        ZipFile zf = new ZipFile(f);

        if (toExtractDir) {
            Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zf.entries();
            ZipEntry ent = null;
            while (entries.hasMoreElements()) {
                ent = entries.nextElement();
                if (isUnderDir(ent, entry)) { //the entry is under directory 
                                              //which should to be extracted.
                                              //extract the entry.
                    extract(zf, ent, desDir, startDirLevel);
                } else {
                    //nothing to do.
                }
            }
        } else {//extract given zip entry file to destination directory.
            ZipEntry zipEntry = zf.getEntry(entry);
            if (null != zipEntry) {
                extract(zf, zipEntry, desDir, startDirLevel);
            }
        }
        if (null != zf) {
            //close zip file.
            zf.close();
        }
    }
}

From source file:com.android.tradefed.util.FileUtil.java

/**
 * Utility method to extract one specific file from zip file into a tmp file
 *
 * @param zipFile/*from  w  w w.jav  a 2  s .  c  om*/
 *            the {@link ZipFile} to extract
 * @param filePath
 *            the filePath of to extract
 * @throws IOException
 *             if failed to extract file
 * @return the {@link File} or null if not found
 */
public static File extractFileFromZip(ZipFile zipFile, String filePath) throws IOException {
    ZipEntry entry = zipFile.getEntry(filePath);
    if (entry == null) {
        return null;
    }
    File createdFile = FileUtil.createTempFile("extracted", FileUtil.getExtension(filePath));
    FileUtil.writeToFile(zipFile.getInputStream(entry), createdFile);
    return createdFile;
}

From source file:org.roda.common.certification.ODFSignatureUtils.java

public static ByteArrayInputStream createSignature(String inputPath, X509Certificate certificate, Key key) {
    try {/*w  w w .ja va2 s .co  m*/
        ZipFile zipFile = new ZipFile(new File(inputPath));

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Init.init();

        XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
        DigestMethod digestMethod = factory.newDigestMethod(DigestMethod.SHA1, null);

        InputStream manifest = zipFile.getInputStream(zipFile.getEntry("META-INF/manifest.xml"));
        Document docManifest = documentBuilder.parse(manifest);
        Element rootManifest = docManifest.getDocumentElement();
        NodeList listFileEntry = rootManifest.getElementsByTagName("manifest:file-entry");
        Document docSignatures;
        Element rootSignatures;

        if (zipFile.getEntry(META_INF_DOCUMENTSIGNATURES_XML) != null) {
            InputStream is = zipFile.getInputStream(zipFile.getEntry(META_INF_DOCUMENTSIGNATURES_XML));
            docSignatures = documentBuilder.parse(is);
            rootSignatures = docSignatures.getDocumentElement();
            IOUtils.closeQuietly(is);
        } else {
            docSignatures = documentBuilder.newDocument();
            rootSignatures = docSignatures.createElement("document-signatures");
            rootSignatures.setAttribute("xmlns", OPENOFFICE);
            docSignatures.appendChild(rootSignatures);

            Element nodeDocumentSignatures = docManifest.createElement("manifest:file-entry");
            nodeDocumentSignatures.setAttribute("manifest:media-type", "");
            nodeDocumentSignatures.setAttribute("manifest:full-path", META_INF_DOCUMENTSIGNATURES_XML);
            rootManifest.appendChild(nodeDocumentSignatures);

            Element nodeMetaInf = docManifest.createElement("manifest:file-entry");
            nodeMetaInf.setAttribute("manifest:media-type", "");
            nodeMetaInf.setAttribute("manifest:full-path", "META-INF/");
            rootManifest.appendChild(nodeMetaInf);
        }

        List<Reference> referenceList = getReferenceList(zipFile, documentBuilder, factory, listFileEntry,
                digestMethod);
        digitalSign(factory, referenceList, digestMethod, certificate, docSignatures, rootSignatures, key);

        ByteArrayOutputStream baos = addSignatureToStream(zipFile, rootManifest, rootSignatures);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        baos.close();
        return bais;

    } catch (Exception e) {
        LOGGER.debug("ODF signature creation went wrong.");
        return null;
    }

}

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

/**
 * read JSON file from JAR file./* w w  w  .ja v  a  2s .co  m*/
 * @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: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 a  v  a 2 s. co  m*/
}

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

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

    try {/*from ww w .  j a v a2 s . c  o m*/
        ZipFile zf = new ZipFile(args[0].getStringValue());
        ZipEntry ze = zf.getEntry(args[1].getStringValue());
        return new IntegerValue(ze.getCrc());
    } catch (Exception e) {
        throw new XPathException("error processing zip file: " + e.getLocalizedMessage(), e);
    }

}

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

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

    try {/* w  ww. j a  v a  2  s .  c  o  m*/
        ZipFile zf = new ZipFile(args[0].getStringValue());
        ZipEntry ze = zf.getEntry(args[1].getStringValue());
        return new IntegerValue(ze.getSize());
    } catch (Exception e) {
        throw new XPathException("error processing zip file: " + e.getLocalizedMessage(), e);
    }

}

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  .  ja  v  a  2s . 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:org.sonatype.flexmojos.tests.issues.Flexmojos247Test.java

@Test
public void includeAsClasses() throws Exception {
    String baseDir = testIssue("flexmojos-247").getBasedir();
    File target = new File(baseDir, "target");
    Assert.assertTrue(target.exists());//from   ww  w .ja v a 2s . c o m

    File swc = new File(target, "flexmojos-247-1.0-SNAPSHOT.swc");
    Assert.assertTrue(swc.exists());

    String catalog;
    ZipFile zf = new ZipFile(swc);
    try {
        InputStream in = zf.getInputStream(zf.getEntry("catalog.xml"));
        catalog = IOUtils.toString(in);
        in.close();
    } finally {
        zf.close();
    }

    // must have both classes and the uri
    MatcherAssert.assertThat(catalog, StringContains.containsString("AClass"));
    MatcherAssert.assertThat(catalog, StringContains.containsString("BClass"));
    MatcherAssert.assertThat(catalog, StringContains.containsString("http://flexmojos.sonatype.org/tests"));
}

From source file:com.espirit.moddev.basicworkflowsTestIT.java

/**
 * Check if FSM is valid//ww w . ja va 2  s .  com
 */
@Test
public void testisFSMValid() {
    try {
        File directory = new File("target");
        Collection files = FileUtils.listFiles(directory, new WildcardFileFilter("*.fsm"), null);
        assertTrue("FSM doesn't contain any files", files.iterator().hasNext());
        if (files.iterator().hasNext()) {
            ZipFile _fsmZip = new ZipFile((File) files.iterator().next());
            ZipEntry fsmEntry = _fsmZip.getEntry(MODULE_DESCRIPTOR);
            assertNotNull("Couldn't find module descriptor (module.xml) in fsm file", fsmEntry);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}