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.obnsoft.ptcm3.MyApplication.java

private boolean downloadZipFile(String url, String target, String fileName, boolean force) {
    if (!force && getFileStreamPath(fileName).exists()) {
        return true;
    }/*from  w w w. jav a2  s . c om*/
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
        ZipInputStream zin = new ZipInputStream(httpResponse.getEntity().getContent());
        for (ZipEntry entry = zin.getNextEntry(); entry != null; entry = zin.getNextEntry()) {
            if (target.equals(entry.getName())) {
                OutputStream out = openFileOutput(fileName, MODE_PRIVATE);
                byte[] buffer = new byte[1024 * 1024];
                int length;
                while ((length = zin.read(buffer)) >= 0) {
                    out.write(buffer, 0, length);
                }
                out.close();
                break;
            }
        }
        zin.close();
    } catch (Exception e) {
        e.printStackTrace();
        getFileStreamPath(fileName).delete();
        return false;
    }
    return true;
}

From source file:com.jadarstudios.rankcapes.bukkit.RankCapesBukkit.java

/**
 * Validates a cape pack and returns true if it is valid.
 *
 * @param pack to validate/*from   w ww .  j  a  v a  2  s.c  om*/
 */
private void validatePack(byte[] pack) throws IOException, InvalidCapePackException, ParseException {
    boolean foundMetadata = false;

    if (pack == null) {
        throw new InvalidCapePackException("The cape pack was null");
    }

    if (!CapePackValidator.isZipFile(pack)) {
        throw new InvalidCapePackException("The cape pack is not a ZIP file.");
    }

    ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(pack));
    ZipEntry entry;

    // reads the zip and finds the files. if the pack config file is not found, return false.
    while ((entry = zipIn.getNextEntry()) != null)
    // if the zip contains a file names "pack.mcmeta"
    {
        if (entry.getName().equals("pack.mcmeta")) {
            foundMetadata = true;
            try {
                this.parseMetadata(zipIn);
            } finally {
                zipIn.close();
            }

            break;
        }
    }

    if (!foundMetadata) {
        throw new InvalidCapePackException("The Cape Pack metadata was not found.");
    }
}

From source file:Main.java

public static String unzip(String filename) throws IOException {
    BufferedOutputStream origin = null;
    String path = null;/*  w  w  w . j a  v a  2s. c o m*/
    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;
}

From source file:com.celements.photo.utilities.Unzip.java

private ByteArrayOutputStream findAndExtractFile(String filename, ZipInputStream zipIn) throws IOException {
    ByteArrayOutputStream out = null;

    for (ZipEntry entry = zipIn.getNextEntry(); zipIn.available() > 0; entry = zipIn.getNextEntry()) {
        if (!entry.isDirectory() && entry.getName().equals(filename)) {
            // read the data and write it to the OutputStream
            int count;
            byte[] data = new byte[BUFFER];
            out = new ByteArrayOutputStream();
            BufferedOutputStream byteOut = new BufferedOutputStream(out, BUFFER);
            while ((count = zipIn.read(data, 0, BUFFER)) != -1) {
                byteOut.write(data, 0, count);
            }//from  w w w .  j a  v a2s . c  o m
            byteOut.flush();
            break;
        }
    }

    zipIn.close();
    return out;
}

From source file:com.wso2mobile.mam.packageExtractor.ZipFileReading.java

public String readiOSManifestFile(String filePath, String name) {
    String plist = "";
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {//from   w  ww.  jav a 2  s  . com
        File file = new File(filePath);
        ZipInputStream stream = new ZipInputStream(new FileInputStream(file));
        try {
            ZipEntry entry;
            while ((entry = stream.getNextEntry()) != null) {
                if (entry.getName().equals("Payload/" + name + ".app/Info.plist")) {
                    InputStream is = stream;

                    int nRead;
                    byte[] data = new byte[16384];

                    while ((nRead = is.read(data, 0, data.length)) != -1) {
                        buffer.write(data, 0, nRead);
                    }

                    buffer.flush();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stream.close();
        }
        NSDictionary rootDict = (NSDictionary) BinaryPropertyListParser.parse(buffer.toByteArray());
        JSONObject obj = new JSONObject();
        obj.put("version", rootDict.objectForKey("CFBundleVersion").toString());
        obj.put("name", rootDict.objectForKey("CFBundleName").toString());
        obj.put("package", rootDict.objectForKey("CFBundleIdentifier").toString());
        plist = obj.toJSONString();
    } catch (Exception e) {
        plist = "Exception occured " + e;
        e.printStackTrace();
    }
    return plist;
}

From source file:org.pdfgal.pdfgalweb.utils.impl.ZipUtilsImpl.java

@Override
public List<String> saveFilesFromZip(final InputStream inputStream) throws IOException {

    final List<String> result = new ArrayList<String>();

    if (inputStream != null) {
        final ZipInputStream zis = new ZipInputStream(inputStream);

        ZipEntry entry = zis.getNextEntry();

        while (entry != null) {
            final byte[] buffer = new byte[1024];
            final String fileName = this.fileUtils.getAutogeneratedName(entry.getName());
            final File file = new File(fileName);

            final FileOutputStream fos = new FileOutputStream(file);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }/*w  ww.  ja v  a2 s.  c  o m*/

            fos.close();
            result.add(fileName);
            entry = zis.getNextEntry();
        }

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

    return result;
}

From source file:com.cloudera.recordservice.tests.ClusterConfiguration.java

/**
 * This method unzips a conf dir return through the CM api and returns the
 * path of the unzipped directory as a string
 *///from   w w  w  .ja  v a  2  s  .co  m
private String unzipConf(String zipFileName) throws IOException {
    int num = rand_.nextInt(10000000);
    String outDir = "/tmp/" + "confDir" + "_" + num + "/";
    byte[] buffer = new byte[4096];
    FileInputStream fis;
    String filename = "";
    fis = new FileInputStream(zipFileName);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        filename = ze.getName();
        File unzippedFile = new File(outDir + filename);
        // Ensure that parent directories exist
        new File(unzippedFile.getParent()).mkdirs();
        FileOutputStream fos = new FileOutputStream(unzippedFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        zis.closeEntry();
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();
    fis.close();
    return outDir + "recordservice-conf/";
}

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

public static void launchMinecraft(String installDir, ModPack pack, LoginResponse resp, boolean isLegacy) {
    try {//from w  ww.j av  a  2s  .  c  om
        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:org.geoserver.wfs.response.ShapeZipTest.java

private String getCharset(final InputStream in) throws IOException {
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry entry = null;/* w  w  w. j  ava 2  s. com*/
    byte[] bytes = new byte[1024];
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.getName().endsWith(".cst")) {
            zis.read(bytes);
        }
    }
    zis.close();

    if (bytes == null)
        return null;
    else
        return new String(bytes).trim();
}

From source file:org.geoserver.wfs.response.ShapeZipTest.java

private String getRequest(final InputStream in) throws IOException {
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry entry = null;//from   www . jav  a  2  s . co  m
    byte[] bytes = new byte[1024];
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.getName().endsWith(".txt")) {
            zis.read(bytes);
        }
    }
    zis.close();

    if (bytes == null)
        return null;
    else
        return new String(bytes).trim();
}