Example usage for java.util.zip ZipFile ZipFile

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

Introduction

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

Prototype

public ZipFile(File file, Charset charset) throws IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:com.aurel.track.lucene.util.FileUtil.java

public static void unzipFile(File uploadZip, File unzipDestinationDirectory) throws IOException {
    if (!unzipDestinationDirectory.exists()) {
        unzipDestinationDirectory.mkdirs();
    }/*  w w  w .j av a 2 s.c  om*/
    final int BUFFER = 2048;
    // Open Zip file for reading
    ZipFile zipFile = new ZipFile(uploadZip, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
        String currentEntry = entry.getName();
        File destFile = new File(unzipDestinationDirectory, currentEntry);
        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        // extract file if not a directory
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            int currentByte;
            // establish buffer for writing file
            byte data[] = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            // read and write until last byte is encountered
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, currentByte);
            }
            dest.flush();
            dest.close();
            is.close();
        }
    }
    zipFile.close();
}

From source file:com.aurel.track.admin.server.dbbackup.DatabaseBackupBL.java

public static Properties getBackupInfo(File backupFile) throws DatabaseBackupBLException {
    Properties prop = new Properties();
    ZipFile zipFile = null;// w  ww .j a  v  a 2s  .c o m

    try {
        zipFile = new ZipFile(backupFile, ZipFile.OPEN_READ);
    } catch (IOException e) {
        throw new DatabaseBackupBLException(e.getMessage(), e);
    }

    ZipEntry zipEntryInfo = zipFile.getEntry(DataReader.FILE_NAME_INFO);
    if (zipEntryInfo == null) {
        try {
            zipFile.close();
        } catch (IOException e) {
            throw new DatabaseBackupBLException(e.getMessage(), e);
        }
        throw new DatabaseBackupBLException("Invalid backup. No file info");
    }

    try {
        prop.load(zipFile.getInputStream(zipEntryInfo));
    } catch (IOException e) {
        throw new DatabaseBackupBLException(e.getMessage(), e);
    }

    try {
        zipFile.close();
    } catch (IOException e) {
        throw new DatabaseBackupBLException(e.getMessage(), e);
    }
    return prop;
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Extract zip data./*from  www. j ava 2s .  co m*/
 * 
 * @param zipData An input stream that represents a zipped file.
 * @return True if finished.
 */
public boolean syncAdd(File zipData) {
    boolean finished = false;
    ZipFile z = null;
    ArrayList<Object[]> media = new ArrayList<Object[]>();
    long sizecnt = 0;
    JSONObject meta = null;
    int nextUsn = 0;
    try {
        z = new ZipFile(zipData, ZipFile.OPEN_READ);
        // get meta info first
        ZipEntry metaEntry = z.getEntry("_meta");
        // if (metaEntry.getSize() >= 100000) {
        // Log.e(AnkiDroidApp.TAG, "Size for _meta entry found too big (" + z.getEntry("_meta").getSize() + ")");
        // return false;
        // }
        meta = new JSONObject(Utils.convertStreamToString(z.getInputStream(metaEntry)));
        ZipEntry usnEntry = z.getEntry("_usn");
        String usnstr = Utils.convertStreamToString(z.getInputStream(usnEntry));
        nextUsn = Integer.parseInt(usnstr);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } catch (ZipException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Then loop through all files
    for (ZipEntry zentry : Collections.list(z.entries())) {
        // Check for zip bombs
        sizecnt += zentry.getSize();
        if (sizecnt > 100 * 1024 * 1024) {
            Log.e(AnkiDroidApp.TAG, "Media zip file exceeds 100MB uncompressed, aborting unzipping");
            return false;
        }
        if (zentry.getName().compareTo("_meta") == 0 || zentry.getName().compareTo("_usn") == 0) {
            // Ignore previously retrieved meta
            continue;
        } else if (zentry.getName().compareTo("_finished") == 0) {
            finished = true;
        } else {
            String name = meta.optString(zentry.getName());
            if (illegal(name)) {
                continue;
            }
            String path = getDir().concat(File.separator).concat(name);
            try {
                Utils.writeToFile(z.getInputStream(zentry), path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String csum = Utils.fileChecksum(path);
            // append db
            media.add(new Object[] { name, csum, _mtime(name) });
            mMediaDb.execute("delete from log where fname = ?", new String[] { name });
        }
    }

    // update media db and note new starting usn
    if (!media.isEmpty()) {
        mMediaDb.executeMany("insert or replace into media values (?,?,?)", media);
    }
    setUsn(nextUsn); // commits
    // if we have finished adding, we need to record the new folder mtime
    // so that we don't trigger a needless scan
    if (finished) {
        syncMod();
    }
    return finished;
}

From source file:fridgegameinstaller.installation.java

public void install(int mb) {

    //check .minecraft exists
    File mclocf = new File(mcloc);

    if (!mclocf.isDirectory()) {
        System.out.println("wrong mc loc");
        mainFrame.errorMsg("Could not find minecraft directory.", "Error");
        mainFrame.setFormToPostInstallation();

    } else {/* w  w  w  .jav a 2 s  .c  om*/
        progmsg.setText("Checking release 1.6.4...");
        //Check 1.6.4 Version exists
        File v164 = new File(mcloc + "/versions/1.6.4");
        if (!v164.exists()) {
            mainFrame.errorMsg(
                    "Could not find release 1.6.4.Start Minecraft with version 1.6.4 before installing Fridgegame.",
                    "Error");
            mainFrame.setFormToPostInstallation();

        } else {
            progmsg.setText("Setting up Fridgegame environment...");
            prgbar.setValue(2);
            //creating Fridgegame version folder
            File vfg = new File(mcloc + "/versions/Fridgegame");
            vfg.mkdir();
            //copy 1.6.4.jar
            File v164jar = new File(mcloc + "/versions/1.6.4/1.6.4.jar");
            File vfgjar = new File(mcloc + "/versions/Fridgegame/Fridgegame.jar");
            try {
                copyFolder(v164jar, vfgjar);
            } catch (IOException e) {
                e.printStackTrace();
                mainFrame.errorMsg("An error occured while dublicating 1.6.4.jar.More information in the log",
                        "Error");
                mainFrame.setFormToPostInstallation();
            }
            progmsg.setText("Setting up natives...");
            prgbar.setValue(5);
            File v164n = new File(mcloc + "/versions/1.6.4/1.6.4-natives");
            File vfgn = new File(mcloc + "/versions/Fridgegame/Fridgegame-natives");
            try {
                copyFolder(v164n, vfgn);
            } catch (IOException e) {

                e.printStackTrace();
                mainFrame.errorMsg("An error occured while dublicating natives.More information in the log",
                        "Error");
                mainFrame.setFormToPostInstallation();
            }
            //init JSON

            progmsg.setText("Setting up basic json...");
            prgbar.setValue(7);
            File vfgjson = new File(mcloc + "/versions/Fridgegame/Fridgegame.json");

            //config json
            try {
                MCJsonConf.getJson(mcloc + "/versions/Fridgegame/Fridgegame.json", mb);
            } catch (IOException e) {
                e.printStackTrace();
                mainFrame.errorMsg(
                        "An error occured while getting json information.More information in the log", "Error");
                mainFrame.setFormToPostInstallation();

            }

            //get json obj
            prgbar.setValue(10);
            progmsg.setText("Fetshing information...");
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("http://api.fridgegame.com/version/");
            JSONObject json;
            String path = "";
            String scala_library_version = "";
            String scala_library_dl_url = "";
            String scala_compiler_version = "";
            String scala_compiler_dl_url = "";
            String forge_version = "";
            String forge_dl_url = "";
            try {
                CloseableHttpResponse response1 = httpclient.execute(httpGet);
                System.out.println(httpGet.toString());
                System.out.println(response1.getStatusLine());
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(response1.getEntity().getContent()));
                String a;
                String output = "";
                while ((a = br.readLine()) != null) {
                    output += a + "\n";
                }
                System.out.println(output);
                try {
                    json = new JSONObject(output);
                    path = json.getString("path");
                    scala_library_version = json.getString("scala_library_version");
                    scala_library_dl_url = json.getString("scala_library_dl_url");
                    scala_compiler_version = json.getString("scala_compiler_version");
                    scala_compiler_dl_url = json.getString("scala_compiler_dl_url");
                    forge_version = json.getString("forge_version");
                    forge_dl_url = json.getString("forge_dl_url");

                } catch (JSONException e) {
                    e.printStackTrace();
                    mainFrame.errorMsg(
                            "An error occured while fetshing information from server.More information in the log",
                            "Error");
                    mainFrame.setFormToPostInstallation();

                }

            } catch (Exception e) {

                e.printStackTrace();
                mainFrame.errorMsg("An error occured.More information in the log", "Error");
                mainFrame.setFormToPostInstallation();

            }
            //scala setup
            progmsg.setText("Checking for latest scala lib...");

            progmsg.setText("Downloading and installing scala lib...");

            prgbar.setValue(15);
            mainFrame.repaint();
            File scalalang = new File(mcloc + "/libraries/org/scala-lang");
            scalalang.mkdir();
            File scalalibdir = new File(mcloc + "/libraries/org/scala-lang/scala-library");
            scalalibdir.mkdir();
            File scalalibverdir = new File(
                    mcloc + "/libraries/org/scala-lang/scala-library/" + scala_library_version);
            scalalibverdir.mkdir();
            File scalalib = new File(mcloc + "/libraries/org/scala-lang/scala-library/" + scala_library_version
                    + "/scala-library-" + scala_library_version + ".jar");
            //##################
            try {
                URL scalalibdlurl = new URL(scala_library_dl_url);
                org.apache.commons.io.FileUtils.copyURLToFile(scalalibdlurl, scalalib);
            } catch (Exception e) {
                e.printStackTrace();
                mainFrame.errorMsg(
                        "An error occured while downloading scala library.More information in the log",
                        "Error");
                mainFrame.setFormToPostInstallation();

            }

            progmsg.setText("Checking for latest scala compiler...");
            prgbar.setValue(30);

            progmsg.setText("Downloading and installing scala compiler...");
            File scalacomdir = new File(mcloc + "/libraries/org/scala-lang/scala-compiler");
            scalacomdir.mkdir();
            File scalacomverdir = new File(
                    mcloc + "/libraries/org/scala-lang/scala-compiler/" + scala_compiler_version);
            scalacomverdir.mkdir();
            File scalacom = new File(mcloc + "/libraries/org/scala-lang/scala-compiler/"
                    + scala_compiler_version + "/scala-compiler-" + scala_compiler_version + ".jar");

            try {
                URL scalacomdlurl = new URL(scala_compiler_dl_url);
                org.apache.commons.io.FileUtils.copyURLToFile(scalacomdlurl, scalacom);
            } catch (Exception e) {
                e.printStackTrace();
                mainFrame.errorMsg(
                        "An error occured while downloading scala compiler.More information in the log",
                        "Error");
                mainFrame.setFormToPostInstallation();

            }
            prgbar.setValue(50);
            progmsg.setText("Checking for latest Minecraft Forge...");

            progmsg.setText("Downloading and installing Minecraft Forge...");

            File mcfidir1 = new File(mcloc + "/libraries/net/minecraftforge");
            File mcfidir2 = new File(mcloc + "/libraries/net/minecraftforge/minecraftforge");
            File mcfidir3 = new File(mcloc + "/libraries/net/minecraftforge/minecraftforge/");
            File mcfidir4 = new File(mcloc + "/libraries/net/minecraftforge/minecraftforge/" + forge_version);

            mcfidir1.mkdir();
            mcfidir2.mkdir();
            mcfidir3.mkdir();
            mcfidir4.mkdir();

            File mcfidir = new File(mcloc + "/libraries/net/minecraftforge/minecraftforge/" + forge_version
                    + "/minecraftforge-" + forge_version + ".jar");

            try {
                URL forgedlurl = new URL(forge_dl_url);
                org.apache.commons.io.FileUtils.copyURLToFile(forgedlurl, mcfidir);
            } catch (Exception e) {
                e.printStackTrace();
                mainFrame.errorMsg(
                        "An error occured while downloading Minecraft Forge.More information in the log",
                        "Error");
                mainFrame.setFormToPostInstallation();

            }

            File fgtemp = new File(mcloc + "/fgtemp");
            fgtemp.mkdir();

            prgbar.setValue(65);

            progmsg.setText("Downloading mods(may take a while)...");
            File fgzipfile = new File(mcloc + "/fgtemp/fg.zip");
            try {
                URL fgzipdlurl = new URL(path);
                org.apache.commons.io.FileUtils.copyURLToFile(fgzipdlurl, fgzipfile);
            } catch (Exception e) {
                e.printStackTrace();
                mainFrame.errorMsg("An error occured while downloading mods.More information in the log",
                        "Error");
                mainFrame.setFormToPostInstallation();
            }
            progmsg.setText("Installing mods...");
            File mclocfile = new File(mcloc);
            prgbar.setValue(85);

            File mclocfilea = new File(mcloc);
            try {
                Charset CP866 = Charset.forName("CP866");
                ZipFile fgzipa = new ZipFile(mcloc + "/fgtemp/fg.zip", CP866);
                unzip(fgzipa, mclocfilea);

            } catch (IOException e) {
                e.printStackTrace();

            }

            if (fgtemp.exists()) {
                try {
                    deletedir(fgtemp);

                } catch (IOException e) {
                    e.printStackTrace();
                    mainFrame.errorMsg("An error occured while deleting temps.More information in the log",
                            "Error");
                    mainFrame.setFormToPostInstallation();
                }
            }

        }
    }
}

From source file:com.blazemeter.bamboo.plugin.ServiceManager.java

public static void unzip(String srcZipFileName, String destDirectoryName, BuildLogger logger) {
    try {// w w w. ja  v a 2s. c om
        BufferedInputStream bufIS = null;
        // create the destination directory structure (if needed)
        File destDirectory = new File(destDirectoryName);
        destDirectory.mkdirs();

        // open archive for reading
        File file = new File(srcZipFileName);
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);

        //for every zip archive entry do
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            logger.addBuildLogEntry("\tExtracting jtl report: " + entry);

            //create destination file
            File destFile = new File(destDirectory, entry.getName());

            //create parent directories if needed
            File parentDestFile = destFile.getParentFile();
            parentDestFile.mkdirs();

            bufIS = new BufferedInputStream(zipFile.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte data[] = new byte[BUFFER_SIZE];

            // write the current file to disk
            FileOutputStream fOS = new FileOutputStream(destFile);
            BufferedOutputStream bufOS = new BufferedOutputStream(fOS, BUFFER_SIZE);

            while ((currentByte = bufIS.read(data, 0, BUFFER_SIZE)) != -1) {
                bufOS.write(data, 0, currentByte);
            }

            // close BufferedOutputStream
            bufOS.flush();
            bufOS.close();
        }
        bufIS.close();
    } catch (Exception e) {
        logger.addErrorLogEntry("Failed to unzip report: check that it is downloaded");
    }
}