Example usage for java.util.zip ZipInputStream ZipInputStream

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

Introduction

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

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:com.moss.fskit.Unzipper.java

public void unzipFile(File zipFile, File destination, boolean unwrap) throws UnzipException {
    try {/* w  ww  .  ja  va2s . c  om*/
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile));
        boolean done = false;
        while (!done) {
            ZipEntry nextEntry = in.getNextEntry();

            if (nextEntry == null)
                done = true;
            else {
                String name = nextEntry.getName();
                if (unwrap) {
                    name = name.substring(name.indexOf('/'));
                }
                File outputFile = new File(destination, name);
                log.info("   " + outputFile.getAbsolutePath());

                if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs())
                    throw new UnzipException("Could not create directory " + outputFile.getParent());

                if (nextEntry.isDirectory()) {
                    if (!outputFile.exists() && !outputFile.mkdir())
                        throw new UnzipException("Ddirectory does not exist and could not be created:"
                                + outputFile.getAbsolutePath());
                } else {
                    if (!outputFile.createNewFile())
                        throw new UnzipException("Could not create file " + outputFile.getAbsolutePath());
                    FileOutputStream out = new FileOutputStream(outputFile);
                    copyStreams(in, out, 1024 * 100);
                    out.close();
                    in.closeEntry();
                }

            }
        }

    } catch (Exception e) {
        throw new UnzipException("There was an error executing the unzip of file " + zipFile.getAbsolutePath(),
                e);
    }

    //      String pathOfZipFile = zipFile.getAbsolutePath();
    //      
    //      String command = "unzip -o "  + pathOfZipFile + " -d " + destination.getAbsolutePath() ;
    //      
    //      try {
    //         log.info("Running " + command);
    //         
    //         int result = new CommandRunner().runCommand(command);
    //         if(result!=0) throw new UnzipException("Unzip command exited with status " + result);
    //         log.info("Unzip complete");
    //      } catch (CommandException e) {
    //         throw new UnzipException("There was an error executing the unzip command: \"" + command + "\"", e);
    //      }
}

From source file:com.facebook.buck.android.AndroidAppBundleIntegrationTest.java

@Test
public void testAppBundleHaveDeterministicTimestamps() throws IOException {
    String target = "//apps/sample:app_bundle_1";
    ProcessResult result = workspace.runBuckCommand("build", target);
    result.assertSuccess();//from  w  w  w.  j  a v  a 2  s .c  o m

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Path aab = workspace.getPath(
            BuildTargetPaths.getGenPath(filesystem, BuildTargetFactory.newInstance(target), "%s.signed.aab"));
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(Files.newInputStream(aab))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }

    ZipInspector zipInspector = new ZipInspector(aab);
    zipInspector.assertFileExists("BundleConfig.pb");
    zipInspector.assertFileExists("base/dex/classes.dex");
    zipInspector.assertFileExists("base/assets.pb");
    zipInspector.assertFileExists("base/resources.pb");
    zipInspector.assertFileExists("base/manifest/AndroidManifest.xml");
    zipInspector.assertFileExists("base/assets/asset_file.txt");
    zipInspector.assertFileExists("base/res/drawable/tiny_black.png");
    zipInspector.assertFileExists("base/native.pb");
    zipInspector.assertFileExists("base/lib/armeabi-v7a/libnative_cxx_lib.so");
    zipInspector.assertFileExists("base/assets/secondary-program-dex-jars/secondary-1.dex.jar");
    NativeLibraries nativeLibraries = NativeLibraries.parseFrom(zipInspector.getFileContents("base/native.pb"));
    assertEquals(3, nativeLibraries.getDirectoryList().size());
    for (TargetedNativeDirectory targetedNativeDirectory : nativeLibraries.getDirectoryList()) {
        assertTrue(targetedNativeDirectory.hasTargeting());
        assertTrue(targetedNativeDirectory.getTargeting().hasAbi());
    }

    Assets assets = Assets.parseFrom(zipInspector.getFileContents("base/assets.pb"));
    for (TargetedAssetsDirectory targetedAssetsDirectory : assets.getDirectoryList()) {
        assertTrue(targetedAssetsDirectory.hasTargeting());
        assertTrue(targetedAssetsDirectory.getTargeting().hasAbi());
    }

    BundleConfig bundleConfig = BundleConfig.parseFrom(zipInspector.getFileContents("BundleConfig.pb"));

    assertTrue(bundleConfig.hasBundletool());
    assertBundletool(bundleConfig.getBundletool());

    assertTrue(bundleConfig.hasOptimizations());
    assertOptimizations(bundleConfig.getOptimizations());

    assertTrue(bundleConfig.hasCompression());
    assertCompression(bundleConfig.getCompression());
}

From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java

private void initialize() {
    this.init = true;

    try {//from   ww w. j  a v a  2 s  .  com
        InputStream in = new FileInputStream(getSourceFile());
        ArrayList<String> itemList = new ArrayList<String>();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        String item = null;
        final int bufLength = 1024;
        char[] buffer = new char[bufLength];
        int readReturn;
        int count = 0;

        ZipEntry zipentry;
        ZipInputStream zipinputstream = new ZipInputStream(in);

        while ((zipentry = zipinputstream.getNextEntry()) != null) {
            count++;
            StringWriter sw = new StringWriter();
            Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8"));

            while ((readReturn = reader.read(buffer)) != -1) {
                sw.write(buffer, 0, readReturn);
            }

            item = new String(sw.toString());
            itemList.add(item);
            this.fileNames.add(zipentry.getName());

            reader.close();
            zipinputstream.closeEntry();

        }

        this.logger.debug("Zip file contains " + count + "elements");
        zipinputstream.close();
        this.counter = 0;

        this.originalData = byteArrayOutputStream.toByteArray();
        this.items = itemList.toArray(new String[] {});
        this.length = this.items.length;
    } catch (Exception e) {
        this.logger.error("Could not read zip File: " + e.getMessage());
        throw new RuntimeException("Error reading input stream", e);
    }
}

From source file:ch.ivyteam.ivy.maven.util.ClasspathJar.java

public String getClasspathUrlEntries() {
    try (ZipInputStream is = new ZipInputStream(new FileInputStream(jar))) {
        Manifest manifest = new Manifest(getInputStream(is, MANIFEST_MF));
        return manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
    } catch (IOException ex) {
        return null;
    }/*from w w w  .  j  a v a 2s  . co  m*/
}

From source file:io.github.jeddict.jcode.util.FileUtil.java

public static void copyStaticResource(String inputTemplatePath, FileObject toDir, String targetFolder,
        ProgressHandler handler) throws IOException {
    InputStream stream = loadResource(inputTemplatePath);
    try (ZipInputStream inputStream = new ZipInputStream(stream)) {
        ZipEntry entry;//  w  w w.  j av  a2  s.c  o m
        while ((entry = inputStream.getNextEntry()) != null) {
            if (entry.getName().lastIndexOf('.') == -1) { //skip if not file
                continue;
            }
            String targetPath = StringUtils.isBlank(targetFolder) ? entry.getName()
                    : targetFolder + '/' + entry.getName();
            if (handler != null) {
                handler.progress(targetPath);
            }
            FileObject target = org.openide.filesystems.FileUtil.createData(toDir, targetPath);
            FileLock lock = target.lock();
            try (OutputStream outputStream = target.getOutputStream(lock)) {
                for (int c = inputStream.read(); c != -1; c = inputStream.read()) {
                    outputStream.write(c);
                }
                inputStream.closeEntry();
            } finally {
                lock.releaseLock();
            }
        }
    }
}

From source file:ZipTest.java

/**
 * Scans the contents of the ZIP archive and populates the combo box.
 *///from ww  w .  j  a  v a2s  .  c o m
public void scanZipFile() {
    new SwingWorker<Void, String>() {
        protected Void doInBackground() throws Exception {
            ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                publish(entry.getName());
                zin.closeEntry();
            }
            zin.close();
            return null;
        }

        protected void process(List<String> names) {
            for (String name : names)
                fileCombo.addItem(name);

        }
    }.execute();
}

From source file:com.graphhopper.reader.osm.OSMInputFile.java

@SuppressWarnings("unchecked")
private InputStream decode(File file) throws IOException {
    final String name = file.getName();

    InputStream ips = null;//w  w  w  . jav  a  2  s.co  m
    try {
        ips = new BufferedInputStream(new FileInputStream(file), 50000);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
    ips.mark(10);

    // check file header
    byte header[] = new byte[6];
    if (ips.read(header) < 0)
        throw new IllegalArgumentException("Input file is not of valid type " + file.getPath());

    /*     can parse bz2 directly with additional lib
     if (header[0] == 'B' && header[1] == 'Z')
     {
     return new CBZip2InputStream(ips);
     }
     */
    if (header[0] == 31 && header[1] == -117) {
        ips.reset();
        return new GZIPInputStream(ips, 50000);
    } else if (header[0] == 0 && header[1] == 0 && header[2] == 0 && header[4] == 10 && header[5] == 9
            && (header[3] == 13 || header[3] == 14)) {
        ips.reset();
        binary = true;
        return ips;
    } else if (header[0] == 'P' && header[1] == 'K') {
        ips.reset();
        ZipInputStream zip = new ZipInputStream(ips);
        zip.getNextEntry();

        return zip;
    } else if (name.endsWith(".osm") || name.endsWith(".xml")) {
        ips.reset();
        return ips;
    } else if (name.endsWith(".bz2") || name.endsWith(".bzip2")) {
        String clName = "org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream";
        try {
            Class clazz = Class.forName(clName);
            ips.reset();
            Constructor<InputStream> ctor = clazz.getConstructor(InputStream.class, boolean.class);
            return ctor.newInstance(ips, true);
        } catch (Exception e) {
            throw new IllegalArgumentException("Cannot instantiate " + clName, e);
        }
    } else {
        throw new IllegalArgumentException("Input file is not of valid type " + file.getPath());
    }
}

From source file:ZipHandler.java

/**
 * unzipps a zip file placed at <zipURL> to path <xmlURL>
 * @param zipURL/* ww  w  .  j av a2s  . c  om*/
 * @param xmlURL
 */
public static void unStructZip(String zipURL, String xmlURL) throws IOException {
    FileInputStream fis = new FileInputStream(new File(zipURL));
    ZipInputStream zis = new ZipInputStream(fis);
    FileOutputStream fos = new FileOutputStream(xmlURL);
    ZipEntry ze = zis.getNextEntry();
    writeInOutputStream(zis, fos);
    fos.flush();
    fis.close();
    fos.close();
    zis.close();
}

From source file:com.magnet.tools.tests.MagnetToolStepDefs.java

@Then("^the package \"([^\"]*)\" should contain the following entries:$")
public static void package_should_contain(String packagePath, List<String> entries) throws Throwable {
    File file = new File(expandVariables(packagePath));
    Assert.assertTrue("File " + file + " should exist", file.exists());

    ZipInputStream zip = null;//ww w .  j a v  a2s .c  o m
    Set<String> actualSet;
    try {
        FileInputStream fis = new FileInputStream(file);
        zip = new ZipInputStream(fis);
        ZipEntry ze;
        actualSet = new HashSet<String>();
        while ((ze = zip.getNextEntry()) != null) {
            actualSet.add(ze.getName());
        }
    } finally {
        if (null != zip) {
            zip.close();
        }
    }

    for (String e : entries) {
        String expected = expandVariables(e);
        Assert.assertTrue("File " + file + " should contain entry " + expected + ", actual set of entries are "
                + actualSet, actualSet.contains(e));
    }
}

From source file:com.thoughtworks.go.server.initializers.CommandRepositoryInitializerIntegrationTest.java

@Test
public void shouldCreateCommandRepositoryWhenNoPreviousRepoExists() throws Exception {
    File defaultCommandRepoDir = TestFileUtil.createTempFolder("default");

    initializer.usePackagedCommandRepository(
            new ZipInputStream(new FileInputStream(getZippedCommandRepo("12.4=12"))), defaultCommandRepoDir);

    assertThat(defaultCommandRepoDir.exists(), is(true));

    assertThat(FileUtils.readFileToString(new File(defaultCommandRepoDir, "version.txt"), UTF_8),
            is("12.4=12"));
    assertThat(new File(defaultCommandRepoDir, "snippet.xml").exists(), is(true));
}