Example usage for java.util.zip ZipInputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:org.jjdltc.cordova.plugin.zip.decompressZip.java

/**
 * Extracts a zip file to a given path//  w  w w  . j a v  a2 s.co  m
 * @param actualTargetPath  Path to un-zip
 * @throws IOException
 */
public boolean doUnZip(String actualTargetPath) throws IOException {
    File target = new File(actualTargetPath);
    if (!target.exists()) {
        target.mkdir();
    }

    ZipInputStream zipFl = new ZipInputStream(new FileInputStream(this.sourceEntry));
    ZipEntry entry = zipFl.getNextEntry();

    while (entry != null) {
        String filePath = actualTargetPath + File.separator + entry.getName();
        if (entry.isDirectory()) {
            File path = new File(filePath);
            path.mkdir();
        } else {
            extractFile(zipFl, filePath);
        }
        zipFl.closeEntry();
        entry = zipFl.getNextEntry();
    }
    zipFl.close();
    return true;
}

From source file:org.n52.movingcode.runtime.codepackage.ZippedPackage.java

/**
 * Static private method that creates an unzipped copy of the archive.
 * // w ww.  j  a va2 s  . c o m
 * @param archive
 *        {@link ZippedPackage}
 * @param workspaceDirName
 *        {@link String}
 * @param targetDirectory
 *        {@link File}
 */
private static void unzipWorkspace(ZippedPackage archive, String workspaceDirName, File targetDirectory) {

    // zipFile and zip url MUST not be null at the same time
    assert (!((archive.zipFile == null) && (archive.zipURL == null)));
    String archiveName = null;

    String wdName = workspaceDirName;
    if (wdName.startsWith("./") || wdName.startsWith(".\\")) {
        wdName = wdName.substring(2);
    }

    try {

        ZipInputStream zis = null;
        if (archive.zipFile != null) {
            zis = new ZipInputStream(new FileInputStream(archive.zipFile));
            archiveName = archive.zipFile.getAbsolutePath();
        } else if (archive.zipURL != null) {
            zis = new ZipInputStream(archive.zipURL.openConnection().getInputStream());
            archiveName = archive.zipURL.toString();
        }

        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (entry.getName().startsWith(wdName)) {

                String fileName = entry.getName();
                File newFile = new File(targetDirectory.getAbsolutePath() + File.separator + fileName);

                // create all required directories
                new File(newFile.getParent()).mkdirs();

                // if current zip entry is not a directory, do unzip
                if (!entry.isDirectory()) {
                    FileOutputStream fos = new FileOutputStream(newFile);
                    IOUtils.copy(zis, fos);
                    fos.close();
                }
            }
            zis.closeEntry();
        }
        if (zis != null) {
            zis.close();
        }
    } catch (ZipException e) {
        logger.error("Error! Could read from archive: " + archiveName);
    } catch (IOException e) {
        logger.error("Error! Could not open archive: " + archiveName);
    } catch (NullPointerException e) {
        logger.error("No archive has been declared. This should not happen ...");
    }
}

From source file:net.ftb.minecraft.MCInstaller.java

public static void launchMinecraft(String installDir, ModPack pack, LoginResponse resp, boolean isLegacy) {
    try {/*w  w w  .j  av  a  2 s.com*/
        File packDir = new File(installDir, pack.getDir());
        String gameFolder = installDir + File.separator + pack.getDir() + File.separator + "minecraft";
        File gameDir = new File(packDir, "minecraft");
        File assetDir = new File(installDir, "assets");
        File libDir = new File(installDir, "libraries");
        File natDir = new File(packDir, "natives");
        final String packVer = Settings.getSettings().getPackVer(pack.getDir());

        Logger.logInfo("Setting up native libraries for " + pack.getName() + " v " + packVer + " MC "
                + pack.getMcVersion(packVer));
        if (!gameDir.exists())
            gameDir.mkdirs();

        if (natDir.exists()) {
            natDir.delete();
        }
        natDir.mkdirs();
        if (isLegacy)
            extractLegacy();
        Version base = JsonFactory.loadVersion(new File(installDir,
                "versions/{MC_VER}/{MC_VER}.json".replace("{MC_VER}", pack.getMcVersion(packVer))));
        byte[] buf = new byte[1024];
        for (Library lib : base.getLibraries()) {
            if (lib.natives != null) {
                File local = new File(libDir, lib.getPathNatives());
                ZipInputStream input = null;
                try {
                    input = new ZipInputStream(new FileInputStream(local));
                    ZipEntry entry = input.getNextEntry();
                    while (entry != null) {
                        String name = entry.getName();
                        int n;
                        if (lib.extract == null || !lib.extract.exclude(name)) {
                            File output = new File(natDir, name);
                            output.getParentFile().mkdirs();
                            FileOutputStream out = new FileOutputStream(output);
                            while ((n = input.read(buf, 0, 1024)) > -1) {
                                out.write(buf, 0, n);
                            }
                            out.close();
                        }
                        input.closeEntry();
                        entry = input.getNextEntry();
                    }
                } catch (Exception e) {
                    ErrorUtils.tossError("Error extracting native libraries");
                    Logger.logError("", e);
                } finally {
                    try {
                        input.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        List<File> classpath = new ArrayList<File>();
        Version packjson = new Version();
        if (!pack.getDir().equals("mojang_vanilla")) {
            if (isLegacy) {
                extractLegacyJson(new File(gameDir, "pack.json"));
            }
            if (new File(gameDir, "pack.json").exists()) {
                packjson = JsonFactory.loadVersion(new File(gameDir, "pack.json"));
                for (Library lib : packjson.getLibraries()) {
                    //Logger.logError(new File(libDir, lib.getPath()).getAbsolutePath());
                    classpath.add(new File(libDir, lib.getPath()));
                }
            }
        } else {
            packjson = base;
        }
        if (!isLegacy) //we copy the jar to a new location for legacy
            classpath.add(new File(installDir,
                    "versions/{MC_VER}/{MC_VER}.jar".replace("{MC_VER}", pack.getMcVersion(packVer))));
        else {
            FileUtils
                    .copyFile(
                            new File(installDir,
                                    "versions/{MC_VER}/{MC_VER}.jar".replace("{MC_VER}",
                                            pack.getMcVersion(packVer))),
                            new File(gameDir, "bin/" + Locations.OLDMCJARNAME));
            FileUtils.killMetaInf();
        }
        for (Library lib : base.getLibraries()) {
            classpath.add(new File(libDir, lib.getPath()));
        }

        Process minecraftProcess = MCLauncher.launchMinecraft(Settings.getSettings().getJavaPath(), gameFolder,
                assetDir, natDir, classpath, packjson.mainClass != null ? packjson.mainClass : base.mainClass,
                packjson.minecraftArguments != null ? packjson.minecraftArguments : base.minecraftArguments,
                packjson.assets != null ? packjson.assets : base.getAssets(),
                Settings.getSettings().getRamMax(), pack.getMaxPermSize(), pack.getMcVersion(packVer),
                resp.getAuth(), isLegacy);
        LaunchFrame.MCRunning = true;
        if (LaunchFrame.con != null)
            LaunchFrame.con.minecraftStarted();
        StreamLogger.prepare(minecraftProcess.getInputStream(), new LogEntry().level(LogLevel.UNKNOWN));
        String[] ignore = { "Session ID is token" };
        StreamLogger.setIgnore(ignore);
        StreamLogger.doStart();
        TrackerUtils.sendPageView(ModPack.getSelectedPack().getName() + " Launched",
                ModPack.getSelectedPack().getName());
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
        }
        try {
            minecraftProcess.exitValue();
        } catch (IllegalThreadStateException e) {
            LaunchFrame.getInstance().setVisible(false);
            LaunchFrame.setProcMonitor(ProcessMonitor.create(minecraftProcess, new Runnable() {
                @Override
                public void run() {
                    if (!Settings.getSettings().getKeepLauncherOpen()) {
                        System.exit(0);
                    } else {
                        if (LaunchFrame.con != null)
                            LaunchFrame.con.minecraftStopped();
                        LaunchFrame launchFrame = LaunchFrame.getInstance();
                        launchFrame.setVisible(true);
                        LaunchFrame.getInstance().getEventBus().post(new EnableObjectsEvent());
                        try {
                            Settings.getSettings()
                                    .load(new FileInputStream(Settings.getSettings().getConfigFile()));
                            LaunchFrame.getInstance().tabbedPane.remove(1);
                            LaunchFrame.getInstance().optionsPane = new OptionsPane(Settings.getSettings());
                            LaunchFrame.getInstance().tabbedPane.add(LaunchFrame.getInstance().optionsPane, 1);
                            LaunchFrame.getInstance().tabbedPane.setIconAt(1, LauncherStyle.getCurrentStyle()
                                    .filterHeaderIcon(this.getClass().getResource("/image/tabs/options.png")));
                        } catch (Exception e1) {
                            Logger.logError("Failed to reload settings after launcher closed", e1);
                        }
                    }
                    LaunchFrame.MCRunning = false;
                }
            }));
        }
    } catch (Exception e) {
        Logger.logError("Error while running launchMinecraft()", e);
    }
}

From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java

/**
 * Adds a zipfile from an inputStream to the aggregate zipfile.
 *
 * @param dirName name of the top-level directory that will be
 * @param inputStream the inputStream to the zipfile created in the aggregate zip file
 * @throws IOException//from  w w w. ja  va  2  s . c o m
 * @throws BadInputZipFileException
 */
private void addZipFileFromInputStream(String dirName, long time, InputStream inputStream)
        throws IOException, BadInputZipFileException {
    // First pass: just scan through the contents of the
    // input file to make sure it's really valid.
    ZipInputStream zipInput = null;
    try {
        zipInput = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            zipInput.closeEntry();
        }
    } catch (IOException e) {
        throw new BadInputZipFileException("Input zip file seems to be invalid", e);
    } finally {
        if (zipInput != null)
            zipInput.close();
    }

    // FIXME: It is probably wrong to call reset() on any input stream; for my application the inputStream will only ByteArrayInputStream or FileInputStream
    inputStream.reset();

    // Second pass: read each entry from the input zip file,
    // writing it to the output file.
    zipInput = null;
    try {
        // add the root directory with the correct timestamp
        if (time > 0L) {
            // Create output entry
            ZipEntry outputEntry = new ZipEntry(dirName + "/");
            outputEntry.setTime(time);
            zipOutput.closeEntry();
        }

        zipInput = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            try {
                String name = entry.getName();
                // Convert absolute paths to relative
                if (name.startsWith("/")) {
                    name = name.substring(1);
                }

                // Prepend directory name
                name = dirName + "/" + name;

                // Create output entry
                ZipEntry outputEntry = new ZipEntry(name);
                if (time > 0L)
                    outputEntry.setTime(time);
                zipOutput.putNextEntry(outputEntry);

                // Copy zip input to output
                CopyUtils.copy(zipInput, zipOutput);
            } catch (Exception zex) {
                // ignore it
            } finally {
                zipInput.closeEntry();
                zipOutput.closeEntry();
            }
        }
    } finally {
        if (zipInput != null) {
            try {
                zipInput.close();
            } catch (IOException ignore) {
                // Ignore
            }
        }
    }
}

From source file:br.eti.ranieri.opcoesweb.importacao.offline.ImportadorOffline.java

public void importar(URL url, ConfiguracaoImportacao configuracaoImportacao) throws Exception {

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new Exception("Requisio HTTP retornou cdigo de erro: " + connection.getResponseCode());
    }//  ww  w  .  j a  v  a 2s .c o m

    List<CotacaoBDI> cotacoes = null;
    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(connection.getInputStream());
        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null) {
            if ("BDIN".equals(entry.getName())) {
                cotacoes = parser.parseBDI(zip);
                zip.closeEntry();
                break;
            } else if (entry.getName().startsWith("COTAHIST_") && entry.getName().endsWith(".TXT")) {
                cotacoes = parser.parseHistorico(zip);
                zip.closeEntry();
                break;
            }
        }
        zip.close();
    } catch (ZipException e) {
        log.error("Formato invalido de arquivo zip", e);
    } catch (IOException e) {
        log.error("Erro de leitura do arquivo zip", e);
    } finally {
        if (zip != null)
            IOUtils.closeQuietly(zip);
    }

    calcularBlackScholes(cotacoes, configuracaoImportacao);
}

From source file:eu.scape_project.up2ti.container.ZipContainer.java

/**
 * Extracts a zip file specified by the zipFilePath to a directory specified by
 * destDirectory (will be created if does not exists)
 * @param containerFileName/*from w  w  w  .  ja v  a2s  .  co  m*/
 * @param destDirectory
 * @throws IOException
 */
public void unzip(String containerFileName, InputStream containerFileStream) throws IOException {
    extractDirectoryName = "/tmp/up2ti_" + RandomStringUtils.randomAlphabetic(10) + "/";
    File destDir = new File(extractDirectoryName);
    destDir.mkdir();
    String subDestDirStr = extractDirectoryName + containerFileName + "/";
    File subDestDir = new File(subDestDirStr);
    subDestDir.mkdir();
    ZipInputStream zipIn = new ZipInputStream(containerFileStream);
    ZipEntry entry = zipIn.getNextEntry();
    while (entry != null) {
        String filePath = subDestDirStr + entry.getName();
        if (!entry.isDirectory()) {
            extractFile(zipIn, filePath);
        } else {
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:eu.scape_project.archiventory.container.ZipContainer.java

/**
 * Extracts a zip file specified by the zipFilePath to a directory specified by
 * destDirectory (will be created if does not exists)
 * @param containerFileName/*w  w  w.  jav a  2  s .  c  o m*/
 * @param destDirectory
 * @throws IOException
 */
public void unzip(String containerFileName, InputStream containerFileStream) throws IOException {
    extractDirectoryName = "/tmp/archiventory_" + RandomStringUtils.randomAlphabetic(10) + "/";
    File destDir = new File(extractDirectoryName);
    destDir.mkdir();
    String subDestDirStr = extractDirectoryName + containerFileName + "/";
    File subDestDir = new File(subDestDirStr);
    subDestDir.mkdir();
    ZipInputStream zipIn = new ZipInputStream(containerFileStream);
    ZipEntry entry = zipIn.getNextEntry();
    while (entry != null) {
        String filePath = subDestDirStr + entry.getName();
        if (!entry.isDirectory()) {
            extractFile(zipIn, filePath);
        } else {
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:abfab3d.shapejs.Project.java

private static void extractZip(String zipFile, String outputFolder, Map<String, String> sceneFiles,
        List<String> resources) {
    byte[] buffer = new byte[1024];

    try {//from  w  ww  .j  a  va  2  s.  co m
        //create output directory is not exists
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            // Ignore directories
            if (ze.isDirectory())
                continue;

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            System.out.println("file unzip : " + newFile.getAbsoluteFile());

            FileOutputStream fos = new FileOutputStream(newFile);

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

            // Save path to the script and parameters files
            if (fileName.endsWith(".json")) {
                sceneFiles.put("paramFile", newFile.getAbsolutePath());
            } else if (fileName.endsWith(".js")) {
                sceneFiles.put("scriptFile", newFile.getAbsolutePath());
            } else {
                resources.add(newFile.getAbsolutePath());
            }

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

        zis.closeEntry();
        zis.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:io.sledge.core.impl.extractor.SledgeApplicationPackageExtractor.java

@Override
public Map<String, InputStream> getPackages(ApplicationPackage appPackage) {
    Map<String, InputStream> packages = new HashMap<>();
    ZipInputStream zipStream = getNewUtf8ZipInputStream(appPackage);

    try {//from w  ww. j av  a  2 s. com
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

        while ((zipEntry = zipStream.getNextEntry()) != null) {

            if (zipEntry.isDirectory()) {
                zipStream.closeEntry();
                continue;
            }

            if (zipEntry.getName().startsWith("packages/")) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();

                int length;
                while ((length = zipStream.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, length);
                }

                String packageFileName = zipEntry.getName().replace("packages/", "");
                packages.put(packageFileName, new ByteArrayInputStream(output.toByteArray()));

                zipStream.closeEntry();
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackage.getPackageFile().reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return packages;
}

From source file:Main.java

public static String unzip(String filename) throws IOException {
    BufferedOutputStream origin = null;
    String path = null;// ww w  .j  a va  2 s. c om
    Integer BUFFER_SIZE = 20480;
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

        File flockedFilesFolder = new File(
                Environment.getExternalStorageDirectory() + File.separator + "FlockLoad");
        System.out.println("FlockedFileDir: " + flockedFilesFolder);
        String compressedFile = flockedFilesFolder.toString() + "/" + filename;
        System.out.println("compressed File name:" + compressedFile);
        //String uncompressedFile = flockedFilesFolder.toString()+"/"+"flockUnZip";
        File purgeFile = new File(compressedFile);

        try {
            ZipInputStream zin = new ZipInputStream(new FileInputStream(compressedFile));
            BufferedInputStream bis = new BufferedInputStream(zin);
            try {
                ZipEntry ze = null;
                while ((ze = zin.getNextEntry()) != null) {
                    byte data[] = new byte[BUFFER_SIZE];
                    path = flockedFilesFolder.toString() + "/" + ze.getName();
                    System.out.println("path is:" + path);
                    if (ze.isDirectory()) {
                        File unzipFile = new File(path);
                        if (!unzipFile.isDirectory()) {
                            unzipFile.mkdirs();
                        }
                    } else {
                        FileOutputStream fout = new FileOutputStream(path, false);
                        origin = new BufferedOutputStream(fout, BUFFER_SIZE);
                        try {
                            /* for (int c = bis.read(data, 0, BUFFER_SIZE); c != -1; c = bis.read(data)) {
                            origin.write(c);
                             }
                             */
                            int count;
                            while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) {
                                origin.write(data, 0, count);
                            }
                            zin.closeEntry();
                        } finally {
                            origin.close();
                            fout.close();

                        }
                    }
                }
            } finally {
                bis.close();
                zin.close();
                purgeFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }
    return null;
}