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.dfki.km.perspecting.obie.corpus.BBCNatureCorpus.java

public Reader getGroundTruth(final URI uri) throws Exception {
    if (labelFileMediaType == MediaType.DIRECTORY) {
        return new StringReader(FileUtils.readFileToString(new File(uri)));
    } else if (labelFileMediaType == MediaType.ZIP) {
        ZipFile zipFile = new ZipFile(labelFolder);
        String[] entryName = uri.toURL().getFile().split("/");
        ZipEntry entry = zipFile/*w  ww .  j a  va2 s.  com*/
                .getEntry(URLDecoder.decode(entryName[entryName.length - 1], "utf-8").replace("text", "rdf"));

        if (entry != null) {
            log.info("found labels for: " + uri.toString());
        } else {
            throw new Exception("did not found labels for: " + uri.toString());
        }
        return new InputStreamReader(zipFile.getInputStream(entry));
    } else {
        throw new Exception("Unsupported media format for labels: " + labelFileMediaType + ". "
                + "Please use zip or plain directories instead.");
    }
}

From source file:de.dfki.km.perspecting.obie.corpus.BBCMusicCorpus.java

public Reader getGroundTruth(final URI uri) throws Exception {
    if (labelFileMediaType == MediaType.DIRECTORY) {
        return new StringReader(FileUtils.readFileToString(new File(uri)));
    } else if (labelFileMediaType == MediaType.ZIP) {
        ZipFile zipFile = new ZipFile(labelFolder);
        String[] entryName = uri.toURL().getFile().split("/");
        ZipEntry entry = zipFile.getEntry(
                URLDecoder.decode(entryName[entryName.length - 1], "utf-8").replace("txt", "dumps") + ".rdf");

        if (entry != null) {
            log.info("found labels for: " + uri.toString());
        } else {//from   w ww . j ava 2s .  c o m
            throw new Exception("did not found labels for: " + uri.toString());
        }
        return new InputStreamReader(zipFile.getInputStream(entry));
    } else {
        throw new Exception("Unsupported media format for labels: " + labelFileMediaType + ". "
                + "Please use zip or plain directories instead.");
    }
}

From source file:com.google.cloud.tools.gradle.appengine.sourcecontext.SourceContextPluginIntegrationTest.java

/** Create a test project with git source context. */
public void setUpTestProject() throws IOException {
    Path buildFile = testProjectDir.getRoot().toPath().resolve("build.gradle");

    Path src = Files.createDirectory(testProjectDir.getRoot().toPath().resolve("src"));
    InputStream buildFileContent = getClass().getClassLoader()
            .getResourceAsStream("projects/sourcecontext-project/build.gradle");
    Files.copy(buildFileContent, buildFile);

    Path gitContext = testProjectDir.getRoot().toPath().resolve("gitContext.zip");
    InputStream gitContextContent = getClass().getClassLoader()
            .getResourceAsStream("projects/sourcecontext-project/gitContext.zip");
    Files.copy(gitContextContent, gitContext);

    try (ZipFile zipFile = new ZipFile(gitContext.toFile())) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(testProjectDir.getRoot(), entry.getName());
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                entryDestination.getParentFile().mkdirs();
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);//from  w  w w  . j  av a  2s  . co  m
                IOUtils.closeQuietly(in);
                out.close();
            }
        }
    }

    FileUtils.delete(gitContext.toFile());

    Path webInf = testProjectDir.getRoot().toPath().resolve("src/main/webapp/WEB-INF");
    Files.createDirectories(webInf);
    File appengineWebXml = Files.createFile(webInf.resolve("appengine-web.xml")).toFile();
    Files.write(appengineWebXml.toPath(), "<appengine-web-app/>".getBytes(Charsets.UTF_8));
}

From source file:com.netflix.nicobar.core.utils.__JDKPaths.java

static void processJar(final Set<String> pathSet, final File file) throws IOException {
    final ZipFile zipFile = new ZipFile(file);
    try {/*from w ww.  jav a  2  s  .  com*/
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final String name = entry.getName();
            final int lastSlash = name.lastIndexOf('/');
            if (lastSlash != -1) {
                pathSet.add(name.substring(0, lastSlash));
            }
        }
        zipFile.close();
    } finally {
        IOUtils.closeQuietly(zipFile);
    }
}

From source file:de.onyxbits.raccoon.appmgr.ExtractWorker.java

@Override
protected File doInBackground() throws Exception {
    ZipFile zip = new ZipFile(source);
    parseResourceTable();/*from  w w  w  .  j  ava  2s  .  c o  m*/
    if (filenames == null) {
        Enumeration<? extends ZipEntry> e = zip.entries();
        Vector<String> tmp = new Vector<String>();
        while (e.hasMoreElements()) {
            tmp.add(e.nextElement().getName());
        }
        filenames = tmp;
    }

    for (String filename : filenames) {
        ZipEntry entry = zip.getEntry(filename);
        InputStream in = zip.getInputStream(entry);
        OutputStream out = openDestination(filename);

        if (isBinaryXml(filename)) {
            XmlTranslator xmlTranslator = new XmlTranslator();
            ByteBuffer buffer = ByteBuffer.wrap(Utils.toByteArray(in));
            BinaryXmlParser binaryXmlParser = new BinaryXmlParser(buffer, resourceTable);
            binaryXmlParser.setLocale(Locale.getDefault());
            binaryXmlParser.setXmlStreamer(xmlTranslator);
            binaryXmlParser.parse();
            IOUtils.write(xmlTranslator.getXml(), out);
        } else {
            // Simply extract
            IOUtils.copy(in, out);
        }
        in.close();
        out.close();
    }

    zip.close();
    return dest;
}

From source file:io.apiman.common.plugin.PluginClassLoader.java

/**
 * Constructor./*from ww  w .  ja  v  a2s. co  m*/
 * @param pluginArtifactFile plugin artifact
 * @param parent parent classloader
 * @throws IOException if an I/O error has occurred
 */
public PluginClassLoader(File pluginArtifactFile, ClassLoader parent) throws IOException {
    super(parent);
    this.pluginArtifactZip = new ZipFile(pluginArtifactFile);
    this.workDir = createWorkDir(pluginArtifactFile);
    indexPluginArtifact();
}

From source file:ClassPath.java

/**
 * Search for classes in given path.//from  ww  w  . ja va  2s  . co m
 */
public ClassPath(String class_path) {
    this.class_path = class_path;
    List vec = new ArrayList();
    for (StringTokenizer tok = new StringTokenizer(class_path, System.getProperty("path.separator")); tok
            .hasMoreTokens();) {
        String path = tok.nextToken();
        if (!path.equals("")) {
            File file = new File(path);
            try {
                if (file.exists()) {
                    if (file.isDirectory()) {
                        vec.add(new Dir(path));
                    } else {
                        vec.add(new Zip(new ZipFile(file)));
                    }
                }
            } catch (IOException e) {
                System.err.println("CLASSPATH component " + file + ": " + e);
            }
        }
    }
    paths = new PathEntry[vec.size()];
    vec.toArray(paths);
}

From source file:com.krawler.esp.fileparser.wordparser.DocxParser.java

public String extractText(String filepath) {
    StringBuilder sb = new StringBuilder();

    ZipFile docxfile = null;/*from  w ww.  java2  s.com*/
    try {
        docxfile = new ZipFile(filepath);
    } catch (Exception e) {
        // file corrupt or otherwise could not be found
        logger.warn(e.getMessage(), e);
        return sb.toString();
    }
    InputStream in = null;
    try {
        ZipEntry ze = docxfile.getEntry("word/document.xml");
        in = docxfile.getInputStream(ze);
    } catch (NullPointerException nulle) {
        System.err.println("Expected entry word/document.xml does not exist");
        logger.warn(nulle.getMessage(), nulle);
        return sb.toString();
    } catch (IOException ioe) {
        logger.warn(ioe.getMessage(), ioe);
        return sb.toString();
    }
    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(in);
    } catch (ParserConfigurationException pce) {
        logger.warn(pce.getMessage(), pce);
        return sb.toString();
    } catch (SAXException sex) {
        sex.printStackTrace();
        return sb.toString();
    } catch (IOException ioe) {
        logger.warn(ioe.getMessage(), ioe);
        return sb.toString();
    } finally {
        try {
            docxfile.close();
        } catch (IOException ioe) {
            System.err.println("Exception closing file.");
            logger.warn(ioe.getMessage(), ioe);
        }
    }
    NodeList list = document.getElementsByTagName("w:t");
    List<String> content = new ArrayList<String>();
    for (int i = 0; i < list.getLength(); i++) {
        Node aNode = list.item(i);
        content.add(aNode.getFirstChild().getNodeValue());
    }
    for (String s : content) {
        sb.append(s);
    }

    return sb.toString();
}

From source file:net.fabricmc.installer.installer.ServerInstaller.java

public static void install(File mcDir, String version, IInstallerProgress progress, File fabricJar)
        throws IOException {
    progress.updateProgress(Translator.getString("gui.installing") + ": " + version, 0);
    String[] split = version.split("-");
    String mcVer = split[0];/*w  w w .  j a  v a2  s.co m*/
    String fabricVer = split[1];

    File mcJar = new File(mcDir, "minecraft_server." + mcVer + ".jar");

    if (!mcJar.exists()) {
        progress.updateProgress(Translator.getString("install.server.downloadVersionList"), 10);
        JsonObject versionList = Utils
                .loadRemoteJSON(new URL("https://launchermeta.mojang.com/mc/game/version_manifest.json"));
        String url = null;

        for (JsonElement element : versionList.getAsJsonArray("versions")) {
            JsonObject object = element.getAsJsonObject();
            if (object.get("id").getAsString().equals(mcVer)) {
                url = object.get("url").getAsString();
                break;
            }
        }

        if (url == null) {
            throw new RuntimeException(Translator.getString("install.server.error.noVersion"));
        }

        progress.updateProgress(Translator.getString("install.server.downloadServerInfo"), 12);
        JsonObject serverInfo = Utils.loadRemoteJSON(new URL(url));
        url = serverInfo.getAsJsonObject("downloads").getAsJsonObject("server").get("url").getAsString();

        progress.updateProgress(Translator.getString("install.server.downloadServer"), 15);
        FileUtils.copyURLToFile(new URL(url), mcJar);
    }

    File libs = new File(mcDir, "libs");

    ZipFile fabricZip = new ZipFile(fabricJar);
    InstallerMetadata metadata;
    try (InputStream inputStream = fabricZip
            .getInputStream(fabricZip.getEntry(Reference.INSTALLER_METADATA_FILENAME))) {
        metadata = new InstallerMetadata(inputStream);
    }

    List<InstallerMetadata.LibraryEntry> fabricDeps = metadata.getLibraries("server", "common");
    for (int i = 0; i < fabricDeps.size(); i++) {
        InstallerMetadata.LibraryEntry dep = fabricDeps.get(i);
        File depFile = new File(libs, dep.getFilename());
        if (depFile.exists()) {
            depFile.delete();
        }
        progress.updateProgress("Downloading " + dep.getFilename(), 20 + (i * 70 / fabricDeps.size()));
        FileUtils.copyURLToFile(new URL(dep.getFullURL()), depFile);
    }

    progress.updateProgress(Translator.getString("install.success"), 100);
}

From source file:com.isomorphic.maven.util.ArchiveUtils.java

/**
 * Unzips the <code>source</code> file to the <code>target</code> directory.
 * /*from  w w w.  java  2 s.  co  m*/
 * @param source The file to be unzipped
 * @param target The directory to which the source file should be unzipped
 * @throws IOException
 */
public static void unzip(File source, File target) throws IOException {

    ZipFile zip = new ZipFile(source);
    Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File file = new File(target, entry.getName());
        FileUtils.copyInputStreamToFile(zip.getInputStream(entry), file);
    }
}