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) throws ZipException, IOException 

Source Link

Document

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

Usage

From source file:de.uni_koeln.spinfo.maalr.services.admin.shared.DataLoader.java

public void createFromSQLDump(File file, int maxEntries)
        throws IOException, NoDatabaseAvailableException, InvalidEntryException, IndexException {

    if (!file.exists()) {
        logger.info("No data to import - file " + file + " does not exist.");
        return;/*from ww w.  ja va2s  .c  o  m*/
    }

    BufferedReader br;
    ZipFile zipFile = null;
    if (file.getName().endsWith(".zip")) {
        logger.info("Trying to read data from zip file=" + file.getName());
        zipFile = new ZipFile(file);
        String entryName = file.getName().replaceAll(".zip", "");
        //         ZipEntry entry = zipFile.getEntry(entryName+".tsv");
        ZipEntry entry = zipFile.getEntry(entryName);
        if (entry == null) {
            logger.info("No file named " + entryName + " found in zip file - skipping import");
            zipFile.close();
            return;
        }
        br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry), "UTF-8"));
    } else {
        logger.info("Trying to read data from file " + file);
        br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    }

    String line = br.readLine();
    String[] keys = line.split("\t", -1);
    Database db = Database.getInstance();
    List<DBObject> entries = new ArrayList<DBObject>();
    int counter = 0;
    String userId = loginManager.getCurrentUserId();
    while ((line = br.readLine()) != null) {
        String[] values = line.split("\t", -1);
        if (values.length != keys.length) {
            logger.warn("Ignoring entry: Attribute mismatch (" + values.length + " entries found, "
                    + keys.length + " entries expected) in line " + line);
            continue;
        }
        LemmaVersion version = new LemmaVersion();
        for (int i = 0; i < keys.length; i++) {
            String value = values[i].trim();
            String key = keys[i].trim();
            if (value.length() == 0)
                continue;
            if (key.length() == 0)
                continue;
            version.setValue(key, value);
        }
        LexEntry entry = new LexEntry(version);
        entry.setCurrent(version);
        entry.getCurrent().setStatus(Status.NEW_ENTRY);
        entry.getCurrent().setVerification(Verification.ACCEPTED);
        long timestamp = System.currentTimeMillis();
        String embeddedTimeStamp = version.getEntryValue(LemmaVersion.TIMESTAMP);
        if (embeddedTimeStamp != null) {
            timestamp = Long.parseLong(embeddedTimeStamp);
            version.removeEntryValue(LemmaVersion.TIMESTAMP);
        }
        entry.getCurrent().setUserId(userId);
        entry.getCurrent().setTimestamp(timestamp);
        entry.getCurrent().setCreatorRole(Role.ADMIN_5);
        entries.add(Converter.convertLexEntry(entry));
        if (entries.size() == 10000) {
            db.insertBatch(entries);
            entries.clear();
        }
        counter++;
        if (counter == maxEntries) {
            logger.warn("Skipping db creation, as max entries is " + maxEntries);
            break;
        }
    }
    db.insertBatch(entries);
    entries.clear();
    //loginManager.login("admin", "admin");
    Iterator<LexEntry> iterator = db.getEntries();
    index.dropIndex();
    index.addToIndex(iterator);
    logger.info("Index has been created, swapping to RAM...");
    index.reloadIndex();
    logger.info("RAM-Index updated.");
    br.close();
    if (zipFile != null) {
        zipFile.close();
    }
    //loginManager.logout();
    logger.info("Dataloader initialized.");
}

From source file:com.phonegap.plugin.files.ExtractZipFilePlugin.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext cbc) {
    PluginResult.Status status = PluginResult.Status.OK;
    try {//from   w w w. j ava 2 s  .  com
        String filename = args.getString(0);
        URL url;
        try {
            url = new URL(filename);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        File file = new File(url.getFile());
        String[] dirToSplit = url.getFile().split(File.separator);
        String dirToInsert = "";
        for (int i = 0; i < dirToSplit.length - 1; i++) {
            dirToInsert += dirToSplit[i] + File.separator;
        }

        ZipEntry entry;
        ZipFile zipfile;
        try {
            zipfile = new ZipFile(file);
            Enumeration e = zipfile.entries();
            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                BufferedInputStream is = null;
                try {
                    is = new BufferedInputStream(zipfile.getInputStream(entry));
                    int count;
                    byte data[] = new byte[102222];
                    String fileName = dirToInsert + entry.getName();
                    File outFile = new File(fileName);
                    if (entry.isDirectory()) {
                        if (!outFile.exists() && !outFile.mkdirs()) {
                            Log.v("info", "Unable to create directories: " + outFile.getAbsolutePath());
                            cbc.sendPluginResult(new PluginResult(IO_EXCEPTION));
                            return false;
                        }
                    } else {
                        File parent = outFile.getParentFile();
                        if (parent.mkdirs()) {
                            Log.v("info", "created directory leading to file");
                        }
                        FileOutputStream fos = null;
                        BufferedOutputStream dest = null;
                        try {
                            fos = new FileOutputStream(outFile);
                            dest = new BufferedOutputStream(fos, 102222);
                            while ((count = is.read(data, 0, 102222)) != -1) {
                                dest.write(data, 0, count);
                            }
                        } finally {
                            if (dest != null) {
                                dest.flush();
                                dest.close();
                            }
                            if (fos != null) {
                                fos.close();
                            }
                        }
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            }
        } catch (ZipException e1) {
            Log.v("error", e1.getMessage(), e1);
            cbc.sendPluginResult(new PluginResult(MALFORMED_URL_EXCEPTION));
            return false;
        } catch (IOException e1) {
            Log.v("error", e1.getMessage(), e1);
            cbc.sendPluginResult(new PluginResult(IO_EXCEPTION));
            return false;
        }

    } catch (JSONException e) {
        cbc.sendPluginResult(new PluginResult(JSON_EXCEPTION));
        return false;
    }
    cbc.sendPluginResult(new PluginResult(status));
    return true;
}

From source file:net.minecrell.quartz.launch.mappings.MappingsLoader.java

public static Mappings load(Logger logger) throws IOException {
    URI source;//from w  w  w  .  j  a v a2  s  .  com
    try {
        source = requireNonNull(Mapping.class.getProtectionDomain().getCodeSource(),
                "Unable to find class source").getLocation().toURI();
    } catch (URISyntaxException e) {
        throw new IOException("Failed to find class source", e);
    }

    Path location = Paths.get(source);
    logger.debug("Mappings location: {}", location);

    List<ClassNode> mappingClasses = new ArrayList<>();

    // Load the classes from the source
    if (Files.isDirectory(location)) {
        // We're probably in development environment or something similar
        // Search for the class files
        Files.walkFileTree(location.resolve(PACKAGE), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {
                    try (InputStream in = Files.newInputStream(file)) {
                        ClassNode classNode = MappingsParser.loadClassStructure(in);
                        mappingClasses.add(classNode);
                    }
                }

                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        // Go through the JAR file
        try (ZipFile zip = new ZipFile(location.toFile())) {
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String name = StringUtils.removeStart(entry.getName(), MAPPINGS_DIR);
                if (entry.isDirectory() || !name.endsWith(".class") || !name.startsWith(PACKAGE_PREFIX)) {
                    continue;
                }

                // Ok, we found something
                try (InputStream in = zip.getInputStream(entry)) {
                    ClassNode classNode = MappingsParser.loadClassStructure(in);
                    mappingClasses.add(classNode);
                }
            }
        }
    }

    return new Mappings(mappingClasses);
}

From source file:com.dibsyhex.apkdissector.ZipReader.java

public void getZipContents(String name) {
    try {/*from  w  ww.  j  a v  a  2 s. c o m*/
        File file = new File(name);
        FileInputStream fileInputStream = new FileInputStream(file);
        ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
        //System.out.println(zipInputStream.available());
        //System.out.println("Reading each entries in details:");
        ZipFile zipFile = new ZipFile(file);
        ZipEntry zipEntry;

        response.displayLog("Begining to extract");

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String filename = "extracts" + File.separator + file.getName() + File.separator
                    + zipEntry.getName();
            System.out.println(filename);
            response.displayLog(filename);
            File extractDirectory = new File(filename);

            //Create the directories
            new File(extractDirectory.getParent()).mkdirs();

            //Now write the contents

            InputStream inputStream = zipFile.getInputStream(zipEntry);
            OutputStream outputStream = new FileOutputStream(extractDirectory);

            FileUtils.copyInputStreamToFile(inputStream, extractDirectory);

            //Decode the xml files

            if (filename.endsWith(".xml")) {
                //First create a temp file at a location temp/extract/...
                File temp = new File("temp" + File.separator + extractDirectory);
                new File(temp.getParent()).mkdirs();

                //Create an object of XML Decoder
                XmlDecoder xmlDecoder = new XmlDecoder();
                InputStream inputStreamTemp = new FileInputStream(extractDirectory);
                byte[] buf = new byte[80000];//increase
                int bytesRead = inputStreamTemp.read(buf);
                String xml = xmlDecoder.decompressXML(buf);
                //System.out.println(xml);
                FileUtils.writeStringToFile(temp, xml);

                //Now rewrite the files at the original locations

                FileUtils.copyFile(temp, extractDirectory);

            }

        }

        response.displayLog("Extraction Done !");
        System.out.println(" DONE ! ");
        zipInputStream.close();

    } catch (Exception e) {
        System.out.println(e.toString());
        response.displayError(e.toString());
    }
}

From source file:io.fabric8.vertx.maven.plugin.utils.WebJars.java

public static void extract(final AbstractVertxMojo mojo, File in, File out, boolean stripVersion)
        throws IOException {
    ZipFile file = new ZipFile(in);
    try {/*from  www .  j a va 2s .  co  m*/
        Enumeration<? extends ZipEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().startsWith(WEBJAR_LOCATION) && !entry.isDirectory()) {
                // Compute destination.
                File output = new File(out, entry.getName().substring(WEBJAR_LOCATION.length()));
                if (stripVersion) {
                    String path = entry.getName().substring(WEBJAR_LOCATION.length());
                    Matcher matcher = WEBJAR_INTERNAL_PATH_REGEX.matcher(path);
                    if (matcher.matches()) {
                        output = new File(out, matcher.group(1) + "/" + matcher.group(3));
                    } else {
                        mojo.getLog().warn(path
                                + " does not match the regex - did not strip the version for this" + " file");
                    }
                }
                InputStream stream = null;
                try {
                    stream = file.getInputStream(entry);
                    output.getParentFile().mkdirs();
                    org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, output);
                } catch (IOException e) {
                    mojo.getLog().error("Cannot unpack " + entry.getName() + " from " + file.getName(), e);
                    throw e;
                } finally {
                    IOUtils.closeQuietly(stream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:net.morematerials.manager.UpdateManager.java

private void updateSmp(File file) throws Exception {
    ZipFile smpFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = smpFile.entries();
    String smpName = file.getName().substring(0, file.getName().lastIndexOf("."));

    // First we need to know what files are in this .smp file, because the old format uses magic filename matching.
    ArrayList<String> containedFiles = new ArrayList<String>();
    HashMap<String, YamlConfiguration> materials = new HashMap<String, YamlConfiguration>();

    // Now we walk through the file once and store every file.
    ZipEntry entry;/*from   www  .j a  v a 2s .c om*/
    YamlConfiguration yaml;
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();

        // Only if its a .yml file
        if (entry.getName().endsWith(".yml")) {
            // Load the .yml file
            yaml = new YamlConfiguration();
            yaml.load(smpFile.getInputStream(entry));

            // Texture is required for new package format.
            if (!yaml.contains("Texture")) {
                materials.put(entry.getName().substring(0, entry.getName().lastIndexOf(".")), yaml);
            } else {
                containedFiles.add(entry.getName());
            }
        } else {
            containedFiles.add(entry.getName());
        }
    }

    // If this map contains any entry, we need to convert something.
    if (materials.size() > 0) {
        this.plugin.getUtilsManager().log("Deprecated .smp found: " + file.getName() + ". Updating...");

        // We need a temporary directory to update the .smp in.
        this.tempDir.mkdir();

        // First extract all untouched assets:
        for (String filename : containedFiles) {
            InputStream in = smpFile.getInputStream(smpFile.getEntry(filename));
            OutputStream out = new FileOutputStream(new File(this.tempDir, filename));
            int read;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
            in.close();
        }

        // Now convert each .yml file in this archive.
        YamlConfiguration oldYaml;
        YamlConfiguration newYaml;
        for (String materialName : materials.keySet()) {
            oldYaml = materials.get(materialName);
            newYaml = new YamlConfiguration();

            // Required "Type" which is Block or Item. Old format didnt support Tools anyway.
            newYaml.set("Type", oldYaml.getString("Type"));
            // Title is now required and falls back to filename.
            newYaml.set("Title", oldYaml.getString("Title", materialName));

            // Now call the converter methods.
            if (newYaml.getString("Type").equals("Block")) {
                this.convertBlock(oldYaml, newYaml, materialName, containedFiles);
                this.convertBlockHandlers(oldYaml, newYaml);
            } else if (newYaml.getString("Type").equals("Item")) {
                this.convertItem(oldYaml, newYaml, materialName, containedFiles);
                this.convertItemHandlers(oldYaml, newYaml);
            }

            // Copy over recipes - nothing changed here!
            if (oldYaml.contains("Recipes")) {
                newYaml.set("Recipes", oldYaml.getList("Recipes"));
            }

            // Finally store the new .yml file.
            String yamlString = newYaml.saveToString();
            BufferedWriter out = new BufferedWriter(
                    new FileWriter(new File(this.tempDir, materialName + ".yml")));
            out.write(this.fixYamlProblems(yamlString));
            out.close();

            // Also update itemmap entry!
            for (Integer i = 0; i < this.itemMap.size(); i++) {
                String oldMaterial = this.itemMap.get(i).replaceAll("^[0-9]+:MoreMaterials.", "");
                if (oldMaterial.equals(newYaml.getString("Title"))) {
                    this.itemMap.set(i, this.itemMap.get(i).replaceAll("^([0-9]+:MoreMaterials.).+$",
                            "$1" + smpName + "." + materialName));
                    break;
                }
            }

            // And we need to tell SpoutPlugin that this material must be renamed!
            SpoutManager.getMaterialManager().renameMaterialKey(this.plugin, newYaml.getString("Title"),
                    smpName + "." + materialName);
        }

        // First remove old .smp file
        smpFile.close();
        file.delete();

        // Then repack the new .smp file
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
        for (File entryFile : this.tempDir.listFiles()) {
            FileInputStream in = new FileInputStream(entryFile);
            out.putNextEntry(new ZipEntry(entryFile.getName()));
            Integer len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
        out.close();

        // At last remove the temp directory.
        FileUtils.deleteDirectory(this.tempDir);
    } else {
        // At last, close the file handle.
        smpFile.close();
    }
}

From source file:de.langmi.spring.batch.examples.readers.file.zip.ZipMultiResourceItemReader.java

/**
 * Tries to extract all files in the archives and adds them as resources to
 * the normal MultiResourceItemReader. Overwrites the Comparator from
 * the super class to get it working with itemstreams.
 *
 * @param executionContext/*  www . jav  a  2  s .  c o m*/
 * @throws ItemStreamException 
 */
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
    // really used with archives?
    if (archives != null) {
        // overwrite the comparator to use description
        // instead of filename, the itemStream can only
        // have that description
        this.setComparator(new Comparator<Resource>() {

            /** Compares resource descriptions. */
            @Override
            public int compare(Resource r1, Resource r2) {
                return r1.getDescription().compareTo(r2.getDescription());
            }
        });
        // get the inputStreams from all files inside the archives
        zipFiles = new ZipFile[archives.length];
        List<Resource> extractedResources = new ArrayList<Resource>();
        try {
            for (int i = 0; i < archives.length; i++) {
                // find files inside the current zip resource
                zipFiles[i] = new ZipFile(archives[i].getFile());
                extractFiles(zipFiles[i], extractedResources);
            }
        } catch (Exception ex) {
            throw new ItemStreamException(ex);
        }
        // propagate extracted resources
        this.setResources(extractedResources.toArray(new Resource[extractedResources.size()]));
    }
    super.open(executionContext);
}

From source file:com.chinamobile.bcbsp.fault.tools.Zip.java

/**
 * Uncompress *.zip files.// w  w w  .  j  ava2  s .c  o m
 * @param fileName
 *        : file to be uncompress
 */
@SuppressWarnings("unchecked")
public static void decompress(String fileName) {
    File sourceFile = new File(fileName);
    String filePath = sourceFile.getParent() + "/";
    try {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration en = zipFile.entries();
        byte[] data = new byte[BUFFER];
        while (en.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) en.nextElement();
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count;
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bis.close();
            bos.close();
        }
        zipFile.close();
    } catch (IOException e) {
        //LOG.error("[compress]", e);
        throw new RuntimeException("[compress]", e);
    }
}

From source file:net.pms.dlna.ZippedEntry.java

@Override
public void push(final OutputStream out) throws IOException {
    Runnable r = new Runnable() {
        InputStream in = null;//ww  w  .  j a v a  2  s. c  om

        public void run() {
            try {
                int n = -1;
                byte[] data = new byte[65536];
                zipFile = new ZipFile(file);
                ZipEntry ze = zipFile.getEntry(zeName);
                in = zipFile.getInputStream(ze);

                while ((n = in.read(data)) > -1) {
                    out.write(data, 0, n);
                }

                in.close();
                in = null;
            } catch (Exception e) {
                logger.error("Unpack error. Possibly harmless.", e);
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    zipFile.close();
                    out.close();
                } catch (IOException e) {
                    logger.debug("Caught exception", e);
                }
            }
        }
    };

    new Thread(r, "Zip Extractor").start();
}

From source file:com.shazam.fork.suite.TestClassScanner.java

private void dumpDexFilesFromApk(File apkFile, File outputFolder) throws IOException {
    ZipFile zip = null;/*from  w  w w  .  jav  a2 s. c  om*/
    InputStream classesDexInputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
        zip = new ZipFile(apkFile);

        int index = 1;
        String currentDex;
        while (true) {
            currentDex = CLASSES_PREFIX + (index > 1 ? index : "") + DEX_EXTENSION;
            ZipEntry classesDex = zip.getEntry(currentDex);
            if (classesDex != null) {
                File dexFileDestination = new File(outputFolder, currentDex);
                classesDexInputStream = zip.getInputStream(classesDex);
                fileOutputStream = new FileOutputStream(dexFileDestination);
                copyLarge(classesDexInputStream, fileOutputStream);
                index++;
            } else {
                break;
            }
        }
    } finally {
        closeQuietly(classesDexInputStream);
        closeQuietly(fileOutputStream);
        closeQuietly(zip);
    }
}