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:edu.harvard.mcz.dwcaextractor.DwCaExtractor.java

/**
 * Setup conditions to run./*from ww  w  . j  a v  a2 s  .c om*/
 * 
 * @param args command line arguments
 * @return true if setup was successful, false otherwise.
 */
protected boolean setup(String[] args) {
    boolean setupOK = false;
    CmdLineParser parser = new CmdLineParser(this);
    //parser.setUsageWidth(4096);
    try {
        parser.parseArgument(args);

        if (help) {
            parser.printUsage(System.out);
            System.exit(0);
        }

        if (archiveFilePath != null) {
            String filePath = archiveFilePath;
            logger.debug(filePath);
            File file = new File(filePath);
            if (!file.exists()) {
                // Error
                logger.error(filePath + " not found.");
            }
            if (!file.canRead()) {
                // error
                logger.error("Unable to read " + filePath);
            }
            if (file.isDirectory()) {
                // check if it is an unzipped dwc archive.
                dwcArchive = openArchive(file);
            }
            if (file.isFile()) {
                // unzip it
                File outputDirectory = new File(file.getName().replace(".", "_") + "_content");
                if (!outputDirectory.exists()) {
                    outputDirectory.mkdir();
                    try {
                        byte[] buffer = new byte[1024];
                        ZipInputStream inzip = new ZipInputStream(new FileInputStream(file));
                        ZipEntry entry = inzip.getNextEntry();
                        while (entry != null) {
                            String fileName = entry.getName();
                            File expandedFile = new File(outputDirectory.getPath() + File.separator + fileName);
                            new File(expandedFile.getParent()).mkdirs();
                            FileOutputStream expandedfileOutputStream = new FileOutputStream(expandedFile);
                            int len;
                            while ((len = inzip.read(buffer)) > 0) {
                                expandedfileOutputStream.write(buffer, 0, len);
                            }

                            expandedfileOutputStream.close();
                            entry = inzip.getNextEntry();
                        }
                        inzip.closeEntry();
                        inzip.close();
                        logger.debug("Unzipped archive into " + outputDirectory.getPath());
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                // look into the unzipped directory
                dwcArchive = openArchive(outputDirectory);
            }
            if (dwcArchive != null) {
                if (checkArchive()) {
                    // Check output 
                    csvPrinter = new CSVPrinter(new FileWriter(outputFilename, append),
                            CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC));
                    // no exception thrown
                    setupOK = true;
                }
            } else {
                System.out.println("Problem opening archive.");
                logger.error("Unable to unpack archive file.");
            }
            logger.debug(setupOK);
        }

    } catch (CmdLineException e) {
        logger.error(e.getMessage());
        parser.printUsage(System.err);
    } catch (IOException e) {
        logger.error(e.getMessage());
        System.out.println(e.getMessage());
        parser.printUsage(System.err);
    }
    return setupOK;
}

From source file:com.yahoo.storm.yarn.TestConfig.java

private void unzipFile(String filePath) {
    FileInputStream fis = null;//from ww  w  . j  a  va2s  .com
    ZipInputStream zipIs = null;
    ZipEntry zEntry = null;
    try {
        fis = new FileInputStream(filePath);
        zipIs = new ZipInputStream(new BufferedInputStream(fis));
        while ((zEntry = zipIs.getNextEntry()) != null) {
            try {
                byte[] tmp = new byte[4 * 1024];
                FileOutputStream fos = null;
                String opFilePath = "lib/" + zEntry.getName();
                if (zEntry.isDirectory()) {
                    LOG.debug("Create a folder " + opFilePath);
                    if (zEntry.getName().indexOf(Path.SEPARATOR) == (zEntry.getName().length() - 1))
                        storm_home = opFilePath.substring(0, opFilePath.length() - 1);
                    new File(opFilePath).mkdir();
                } else {
                    LOG.debug("Extracting file to " + opFilePath);
                    fos = new FileOutputStream(opFilePath);
                    int size = 0;
                    while ((size = zipIs.read(tmp)) != -1) {
                        fos.write(tmp, 0, size);
                    }
                    fos.flush();
                    fos.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        zipIs.close();
    } catch (FileNotFoundException e) {
        LOG.warn(e.toString());
    } catch (IOException e) {
        LOG.warn(e.toString());
    }
    LOG.info("storm_home: " + storm_home);
}

From source file:org.statmantis.mport.retro.event.RetrosheetEventReader.java

@Override
protected EventInformation read(InputStream stream) throws IOException {
    ZipInputStream zis = new ZipInputStream(stream);
    try {//from ww  w  .ja  v a 2  s .c  o m
        EventInformation info = new EventInformation();
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(zis));
                if (entry.getName().equals("TEAM" + year)) {
                    readTeamFile(entry.getName(), reader, info);
                } else if (entry.getName().endsWith(".ROS")) {
                    readRosterFile(entry.getName(), reader, info);
                } else if (entry.getName().endsWith(".EVA") || entry.getName().endsWith(".EVN")
                        || entry.getName().endsWith(".eba") || entry.getName().endsWith(".ebn")) {
                    readEventFile(entry.getName(), reader, info);
                } else {
                    throw new RetrosheetRuntimeException("Unknown zip entry: " + entry);
                }
            } catch (Exception e) {
                throw new RetrosheetRuntimeException("Error reading zip entry " + entry.getName(), e);
            }
            entry = zis.getNextEntry();
        }
        return info;
    } finally {
        try {
            zis.close();
        } catch (Exception e) {
            //no-op
        }
    }
}

From source file:com.pari.nm.modules.jobs.VSEMImporter.java

private VSEFileProcessor getVSE(File pcb, String pcbFileName, File rootDir)
        throws IOException, PariAPIException {
    if (!pcb.isDirectory()) {
        logger.debug("Unzipping " + pcbFileName + " to " + rootDir.getAbsolutePath());
        FileInputStream fis = new FileInputStream(pcb);
        ZipInputStream zin = new ZipInputStream(fis);
        try {//from  www .  j  av a2 s. co  m
            UnzipDir.unzip2(pcbFileName, rootDir.getAbsolutePath());
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (zin != null) {
                zin.close();
            }
        }
        logger.debug("Done unzipping " + pcbFileName + " to " + rootDir.getAbsolutePath());
    }
    VSEFileProcessor fp = openVSEM(pcbFileName, rootDir);
    logger.debug("Done opening VSEM file.");
    return fp;
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

public String loadTouchOscXML(String zipTouchoscFilePath) {
    List<String> touchoscFilePathList = new ArrayList<String>();
    IPath path = new Path(zipTouchoscFilePath);
    String xml = "";
    try {/*from   ww w . j av a 2  s  .  c om*/
        FileInputStream touchoscFile = new FileInputStream(zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);
        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(path.removeLastSegments(1) + "/_" + path.lastSegment());
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.flip();

            xml = charBuffer.toString();

        }

        fileIS.close();

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    return xml;
}

From source file:org.apache.axis2.deployment.repository.util.ArchiveReader.java

/**
 * Extracts Service XML files and builds the service groups.
 *
 * @param filename/*w ww . j  ava 2s.  c o  m*/
 * @param axisServiceGroup
 * @param extractService
 * @param wsdlServices
 * @param configCtx
 * @return Returns ArrayList.
 * @throws DeploymentException
 */
public ArrayList<AxisService> processServiceGroup(String filename, DeploymentFileData currentFile,
        AxisServiceGroup axisServiceGroup, boolean extractService, HashMap<String, AxisService> wsdlServices,
        ConfigurationContext configCtx) throws AxisFault {
    // get attribute values
    if (!extractService) {
        ZipInputStream zin = null;
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(filename);
            zin = new ZipInputStream(fin);
            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                if (entry.getName().equalsIgnoreCase(SERVICES_XML)) {
                    axisServiceGroup
                            .setServiceGroupName(DescriptionBuilder.getShortFileName(currentFile.getName()));
                    return buildServiceGroup(zin, currentFile, axisServiceGroup, wsdlServices, configCtx);
                }
            }
            throw new DeploymentException(
                    Messages.getMessage(DeploymentErrorMsgs.SERVICE_XML_NOT_FOUND, filename));
        } catch (Exception e) {
            throw new DeploymentException(e);
        } finally {
            if (zin != null) {
                try {
                    zin.close();
                } catch (IOException e) {
                    log.info(Messages.getMessage("errorininputstreamclose"));
                }
            }
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    log.info(Messages.getMessage("errorininputstreamclose"));
                }
            }
        }
    } else {
        File file = new File(filename, SERVICES_XML);
        if (!file.exists()) {
            // try for meta-inf
            file = new File(filename, SERVICES_XML.toLowerCase());
        }
        if (file.exists()) {
            InputStream in = null;
            try {
                in = new FileInputStream(file);
                axisServiceGroup.setServiceGroupName(currentFile.getName());
                return buildServiceGroup(in, currentFile, axisServiceGroup, wsdlServices, configCtx);
            } catch (FileNotFoundException e) {
                throw new DeploymentException(
                        Messages.getMessage(DeploymentErrorMsgs.FILE_NOT_FOUND, e.getMessage()));
            } catch (XMLStreamException e) {
                throw new DeploymentException(
                        Messages.getMessage(DeploymentErrorMsgs.XML_STREAM_EXCEPTION, e.getMessage()));
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        log.info(Messages.getMessage("errorininputstreamclose"));
                    }
                }
            }
        } else {
            throw new DeploymentException(Messages.getMessage(DeploymentErrorMsgs.SERVICE_XML_NOT_FOUND));
        }
    }
}

From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java

private void removeFileInZipContaining(List<String> contentFilter, File zipFile)
        throws ZipException, IOException {
    ZipScanner zs = new ZipScanner();
    zs.setSrc(zipFile);/*  ww w. j  a va 2  s  .c  o  m*/
    String[] includes = { "**/*.process" };
    zs.setIncludes(includes);
    //zs.setCaseSensitive(true);
    zs.init();
    zs.scan();

    File originalProjlib = zipFile; // to be overwritten
    File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read
    FileUtils.copyFile(originalProjlib, tmpProjlib);

    ZipFile listZipFile = new ZipFile(tmpProjlib);
    ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib));
    ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib));

    ZipEntry zipEntry;
    boolean keep;
    while ((zipEntry = readZipFile.getNextEntry()) != null) {
        keep = true;
        for (String filter : contentFilter) {
            keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry));
        }
        //         if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry))
        //          && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) {
        if (keep) {
            writeZipFile.putNextEntry(zipEntry);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = readZipFile.read(buf)) >= 0) {
                writeZipFile.write(buf, 0, len);
            }
            writeZipFile.closeEntry();
            //getLog().info("written");
        } else {
            getLog().info("removed " + zipEntry.getName());
        }

    }

    writeZipFile.close();
    readZipFile.close();
    listZipFile.close();

    originalProjlib.setLastModified(originalProjlib.lastModified() - 100000);
}

From source file:com.facebook.buck.jvm.java.DefaultJavaLibraryIntegrationTest.java

@Test
public void testSpoolClassFilesDirectlyToJar() throws IOException {
    setUpProjectWorkspaceForScenario("spool_class_files_directly_to_jar");

    BuildTarget target = BuildTargetFactory.newInstance("//:a");
    ProcessResult result = workspace.runBuckBuild(target.getFullyQualifiedName());
    result.assertSuccess();/*from  w w w . ja v a 2  s.c  o m*/

    Path classesDir = workspace.getPath(CompilerOutputPaths.of(target, filesystem).getClassesDir());

    assertThat(Files.exists(classesDir), is(Boolean.TRUE));
    assertThat("There should be no class files in disk", ImmutableList.copyOf(classesDir.toFile().listFiles()),
            hasSize(0));

    Path jarPath = workspace.getPath(CompilerOutputPaths.getOutputJarPath(target, filesystem));
    assertTrue(Files.exists(jarPath));
    ZipInputStream zip = new ZipInputStream(new FileInputStream(jarPath.toFile()));
    assertThat(zip.getNextEntry().getName(), is("META-INF/"));
    assertThat(zip.getNextEntry().getName(), is("META-INF/MANIFEST.MF"));
    assertThat(zip.getNextEntry().getName(), is("A.class"));
    assertThat(zip.getNextEntry().getName(), is("B.class"));
    zip.close();
}

From source file:configuration.Util.java

/**
 * This un-ZIP a the input_filename to the output_filename
 * @param input_filename//w  ww.  ja  va  2 s  .  c o m
 * @param output_filename
 * @return True if success
 */
public static boolean unzip(String input_filename, String output_filename) {
    try {
        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(input_filename));
        OutputStream out = new FileOutputStream(output_filename);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = zipInputStream.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        zipInputStream.close();
        out.close();
        return true;
    } catch (Exception e) {
        System.out.println("Unzip Failed!");
        System.out.println(e);
        e.printStackTrace();
        return false;
    }
}

From source file:org.inaturalist.android.GuideXML.java

/**
 * Extracts a downloaded NGZ file into the offline guide directory
 * @param ngzFilename the NGZ file path/*from  w ww  .  j  a  v a  2s . c om*/
 * @return true/false status
 */
public boolean extractOfflineGuide(String ngzFilename) {
    // First, create the offline guide directory, if it doesn't exist
    File offlineGuidesDir = new File(mContext.getExternalCacheDir() + OFFLINE_GUIDE_PATH + mGuideId);
    offlineGuidesDir.mkdirs();

    // Next, extract the NGZ file into that directory
    String basePath = offlineGuidesDir.getPath();
    InputStream is;
    ZipInputStream zis;
    try {
        String filename;
        is = new FileInputStream(ngzFilename);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

        // Extract all files in the zip file - one by one
        while ((ze = zis.getNextEntry()) != null) {
            // Get current filename
            filename = ze.getName();

            // Need to create directories if doesn't exist, or it will generate an Exception...
            if (ze.isDirectory()) {
                File fmd = new File(basePath + "/" + filename);
                fmd.mkdirs();
                continue;
            }

            FileOutputStream fout = new FileOutputStream(basePath + "/" + filename);

            // Extract current file
            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
            }

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

        zis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}