Example usage for java.util.zip ZipFile getInputStream

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

Introduction

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

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:com.sshtools.j2ssh.util.ExtensionClassLoader.java

private byte[] loadClassFromZipfile(File file, String name, ClassCacheEntry cache) throws IOException {
    // Translate class name to file name
    String classFileName = name.replace('.', '/') + ".class";

    ZipFile zipfile = new ZipFile(file);

    try {//from ww w .java 2  s. c o m
        ZipEntry entry = zipfile.getEntry(classFileName);

        if (entry != null) {
            if (cache != null) {
                cache.origin = file;

            }
            return loadBytesFromStream(zipfile.getInputStream(entry), (int) entry.getSize());
        } else {
            // Not found
            return null;
        }
    } finally {
        zipfile.close();
    }
}

From source file:org.dspace.content.packager.AbstractMETSIngester.java

/**
 * Retrieve the inputStream for a File referenced from a specific path
 * within a METS package.//from  www  .j  a v  a  2 s  . c  o m
 * <p>
 * If the packager is set to 'manifest-only' (i.e. pkgFile is just a
 * manifest), we assume the file is available for download via a URL.
 * <p>
 * Otherwise, the pkgFile is a Zip, so the file should be retrieved from
 * within that Zip package.
 * 
 * @param pkgFile
 *            the full package file (which may include content files if a
 *            zip)
 * @param params
 *            Parameters passed to METSIngester
 * @param path
 *            the File path (either path in Zip package or a URL)
 * @return the InputStream for the file
 * @throws MetadataValidationException if validation error
 * @throws IOException if IO error
 */
protected static InputStream getFileInputStream(File pkgFile, PackageParameters params, String path)
        throws MetadataValidationException, IOException {
    // If this is a manifest only package (i.e. not a zip file)
    if (params.getBooleanProperty("manifestOnly", false)) {
        // NOTE: since we are only dealing with a METS manifest,
        // we will assume all external files are available via URLs.
        try {
            // attempt to open a connection to given URL
            URL fileURL = new URL(path);
            URLConnection connection = fileURL.openConnection();

            // open stream to access file contents
            return connection.getInputStream();
        } catch (IOException io) {
            log.error("Unable to retrieve external file from URL '" + path
                    + "' for manifest-only METS package.  All externally referenced files must be retrievable via URLs.");
            // pass exception upwards
            throw io;
        }
    } else {
        // open the Zip package
        ZipFile zipPackage = new ZipFile(pkgFile);

        // Retrieve the manifest file entry by name
        ZipEntry manifestEntry = zipPackage.getEntry(path);

        // Get inputStream associated with this file
        if (manifestEntry != null)
            return zipPackage.getInputStream(manifestEntry);
        else {
            throw new MetadataValidationException(
                    "Manifest file references file '" + path + "' not included in the zip.");
        }
    }
}

From source file:net.sf.asap.Player.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Uri uri = getIntent().getData();/* w w w .j  av a2 s. c o  m*/
    filename = uri.getLastPathSegment();
    ZipFile zip = null;
    final byte[] module = new byte[ASAPInfo.MAX_MODULE_LENGTH];
    int moduleLen;
    try {
        InputStream is;
        if (Util.isZip(filename)) {
            zip = new ZipFile(uri.getPath());
            filename = uri.getFragment();
            is = zip.getInputStream(zip.getEntry(filename));
        } else {
            try {
                is = getContentResolver().openInputStream(uri);
            } catch (FileNotFoundException ex) {
                if (uri.getScheme().equals("http"))
                    is = httpGet(uri);
                else
                    throw ex;
            }
        }
        moduleLen = readAndClose(is, module);
    } catch (IOException ex) {
        showError(R.string.error_reading_file);
        return;
    } finally {
        Util.close(zip);
    }
    try {
        asap.load(filename, module, moduleLen);
    } catch (Exception ex) {
        showError(R.string.invalid_file);
        return;
    }
    info = asap.getInfo();

    setTitle(R.string.playing_title);
    setContentView(R.layout.playing);
    setTag(R.id.name, info.getTitleOrFilename());
    setTag(R.id.author, info.getAuthor());
    setTag(R.id.date, info.getDate());
    findViewById(R.id.stop_button).setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
    mediaController = new MediaController(this, false);
    mediaController.setAnchorView(getContentView());
    mediaController.setMediaPlayer(new MediaController.MediaPlayerControl() {
        public boolean canPause() {
            return !isPaused();
        }

        public boolean canSeekBackward() {
            return false;
        }

        public boolean canSeekForward() {
            return false;
        }

        public int getBufferPercentage() {
            return 100;
        }

        public int getCurrentPosition() {
            return asap.getPosition();
        }

        public int getDuration() {
            return info.getDuration(song);
        }

        public boolean isPlaying() {
            return !isPaused();
        }

        public void pause() {
            audioTrack.pause();
        }

        public void seekTo(int pos) {
            seek(pos);
        }

        public void start() {
            resume();
        }
    });
    if (info.getSongs() > 1) {
        mediaController.setPrevNextListeners(new OnClickListener() {
            public void onClick(View v) {
                playNextSong();
            }
        }, new OnClickListener() {
            public void onClick(View v) {
                playPreviousSong();
            }
        });
    }
    new Handler().postDelayed(new Runnable() {
        public void run() {
            mediaController.show();
        }
    }, 500);

    stop = false;
    playSong(info.getDefaultSong());
    new Thread(this).start();
}

From source file:fi.mikuz.boarder.gui.ZipImporter.java

private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {

    File outputFile = new File(outputDir, entry.getName());

    if (entry.isDirectory()) {
        createDir(outputFile);/* www .  j  a v a 2 s .co  m*/
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }

    log = "Extracting: " + entry.getName() + "\n" + log;
    postMessage("Please wait\n\n" + log);
    Log.d(TAG, "Extracting: " + entry);
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    try {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }

}

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);//from w  w w .j a va2 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:net.sourceforge.jweb.maven.mojo.InWarMinifyMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled)
        return;/*from  www .j a  v  a 2 s . c om*/
    processConfiguration();
    String name = this.getBuilddir().getAbsolutePath() + File.separator + this.getFinalName() + "."
            + this.getPacking();
    this.getLog().info(name);
    MinifyFileFilter fileFilter = new MinifyFileFilter();
    int counter = 0;
    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            //no compress, just transfer to war
            if (!fileFilter.accept(entry)) {
                getLog().debug("nocompress entry: " + entry.getName());
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }

            File sourceTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".tmp");
            File destTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".min.tmp");
            FileUtils.writeStringToFile(sourceTmp, "");
            FileUtils.writeStringToFile(destTmp, "");

            //assemble arguments
            String[] provied = getYuiArguments();
            int length = (provied == null ? 0 : provied.length);
            length += 5;
            int i = 0;

            String[] ret = new String[length];

            ret[i++] = "--type";
            ret[i++] = (entry.getName().toLowerCase().endsWith(".css") ? "css" : "js");

            if (provied != null) {
                for (String s : provied) {
                    ret[i++] = s;
                }
            }

            ret[i++] = sourceTmp.getAbsolutePath();
            ret[i++] = "-o";
            ret[i++] = destTmp.getAbsolutePath();

            try {
                InputStream in = zipFile.getInputStream(entry);
                FileUtils.copyInputStreamToFile(in, sourceTmp);
                in.close();

                YUICompressorNoExit.main(ret);
            } catch (Exception e) {
                this.getLog().warn("compress error, this file will not be compressed:" + buildStack(e));
                FileUtils.copyFile(sourceTmp, destTmp);
            }

            out.putNextEntry(new ZipEntry(entry.getName()));
            InputStream compressedIn = new FileInputStream(destTmp);
            byte[] buf = new byte[512];
            int len = -1;
            while ((len = compressedIn.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            compressedIn.close();

            String sourceSize = decimalFormat.format(sourceTmp.length() * 1.0d / 1024) + " KB";
            String destSize = decimalFormat.format(destTmp.length() * 1.0d / 1024) + " KB";
            getLog().info("compressed entry:" + entry.getName() + " [" + sourceSize + " ->" + destSize + "/"
                    + numberFormat.format(1 - destTmp.length() * 1.0d / sourceTmp.length()) + "]");

            counter++;
        }
        zipFile.close();
        out.close();

        FileUtils.cleanDirectory(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
        FileUtils.forceDelete(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:es.eucm.eadandroid.homeapp.repository.resourceHandler.RepoResourceHandler.java

/**
 * Uncompresses any zip file/*  www  . ja  v a  2  s.  c  o m*/
 */
public static void unzip(String path_from, String path_to, String name, boolean deleteZip) {

    StringTokenizer separator = new StringTokenizer(name, ".", true);
    String file_name = separator.nextToken();

    File f = new File(path_to + file_name);

    if (f.exists())
        removeDirectory(f);

    separator = new StringTokenizer(path_to + file_name, "/", true);

    String partial_path = null;
    String total_path = separator.nextToken();

    while (separator.hasMoreElements()) {

        partial_path = separator.nextToken();
        total_path = total_path + partial_path;
        if (!new File(total_path).exists()) {

            if (separator.hasMoreElements())
                total_path = total_path + separator.nextToken();
            else
                (new File(total_path)).mkdir();

        } else
            total_path = total_path + separator.nextToken();

    }

    Enumeration<? extends ZipEntry> entries = null;
    ZipFile zipFile = null;

    try {
        String location_ead = path_from + name;
        zipFile = new ZipFile(location_ead);

        entries = zipFile.entries();

        BufferedOutputStream file;

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            separator = new StringTokenizer(entry.getName(), "/", true);
            partial_path = null;
            total_path = "";

            while (separator.hasMoreElements()) {

                partial_path = separator.nextToken();
                total_path = total_path + partial_path;
                if (!new File(entry.getName()).exists()) {

                    if (separator.hasMoreElements()) {
                        total_path = total_path + separator.nextToken();
                        (new File(path_to + file_name + "/" + total_path)).mkdir();
                    } else {

                        file = new BufferedOutputStream(
                                new FileOutputStream(path_to + file_name + "/" + total_path));

                        System.err.println("Extracting file: " + entry.getName());
                        copyInputStream(zipFile.getInputStream(entry), file);
                    }
                } else {
                    total_path = total_path + separator.nextToken();
                }
            }

        }

        zipFile.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return;
    }

    if (deleteZip)
        (new File(path_from + name)).delete();

}

From source file:fr.ippon.wip.config.ZipConfiguration.java

/**
 * Extract the files related to the configuration of the given name.
 * //from w w  w  .j a v  a2s .c  o  m
 * @param zipFile
 * @param configurationName
 * @return
 * @throws IOException
 */
private boolean extract(ZipFile zipFile, String configurationName) throws IOException {
    XMLConfigurationDAO xmlConfigurationDAO = new XMLConfigurationDAO(FileUtils.getTempDirectoryPath());
    File file;
    ZipEntry entry;
    int[] types = new int[] { XMLConfigurationDAO.FILE_NAME_CLIPPING, XMLConfigurationDAO.FILE_NAME_TRANSFORM,
            XMLConfigurationDAO.FILE_NAME_CONFIG };
    for (int type : types) {
        file = xmlConfigurationDAO.getConfigurationFile(configurationName, type);
        entry = zipFile.getEntry(file.getName());
        if (entry == null)
            return false;

        copy(zipFile.getInputStream(entry), FileUtils.openOutputStream(file));
    }

    return true;
}

From source file:org.bdval.ConsensusBDVModel.java

/**
 * @param options specific options to use when loading the properties
 * @throws IOException if there is a problem accessing the properties
 *//*from w  w  w.j  ava 2s.  c o m*/
private void loadProperties(final DAVOptions options) throws IOException {
    final boolean zipExists = new File(zipFilename).exists();
    if (LOG.isDebugEnabled()) {
        LOG.debug("model zip file exists: " + BooleanUtils.toStringYesNo(zipExists));
    }

    properties.clear();

    // check to see if a zip file exists - if it doesn't we assume it's an old binary format
    if (zipModel && zipExists) {
        LOG.info("Reading model from filename: " + zipFilename);

        final ZipFile zipFile = new ZipFile(zipFilename);
        try {
            final ZipEntry propertyEntry = zipFile.getEntry(FilenameUtils.getName(modelPropertiesFilename));
            // load properties
            properties.clear();
            properties.addAll(loadProperties(zipFile.getInputStream(propertyEntry), options));
        } finally {
            try {
                zipFile.close();
            } catch (IOException e) { // NOPMD
                // ignore since there is not much we can do anyway
            }
        }
    } else {
        final File propertyFile = new File(modelFilenamePrefix + "." + ModelFileExtension.props.toString());
        if (propertyFile.exists() && propertyFile.canRead()) {
            LOG.debug("Loading properties from " + propertyFile.getAbsolutePath());
            properties.addAll(loadProperties(FileUtils.openInputStream(propertyFile), options));
        }
    }
}

From source file:org.gitools.matrix.format.TdmMatrixFormat.java

private MTabixIndex readMtabixIndex(IResourceLocator resourceLocator, IProgressMonitor progressMonitor)
        throws IOException, URISyntaxException {

    // Check if we are using mtabix
    URL dataURL = resourceLocator.getURL();

    URL indexURL = null;//from ww w  .  ja v a  2s .c o m

    if (!dataURL.getPath().endsWith("zip")) {
        IResourceLocator mtabix = resourceLocator.getReferenceLocator(resourceLocator.getName() + ".gz.mtabix");
        indexURL = mtabix.getURL();
    } else {
        //ZipFile zipFile = new ZipFile(new File(dataURL.toURI()));
        ZipFile zipFile = new ZipFile(resourceLocator.getReadFile());
        ZipEntry entry = zipFile.getEntry(resourceLocator.getName() + ".gz.mtabix");

        if (entry == null) {
            return null;
        }

        // Copy index to a temporal file
        File indexFile = File.createTempFile("gitools-cache-", "zip_mtabix");
        indexFile.deleteOnExit();
        IOUtils.copy(zipFile.getInputStream(entry), new FileOutputStream(indexFile));
        indexURL = indexFile.toURL();

        // Copy data to a temporal file
        File dataFile = File.createTempFile("gitools-cache-", "zip_bgz");
        dataFile.deleteOnExit();

        InputStream dataStream = resourceLocator.getParentLocator().openInputStream(progressMonitor);

        IOUtils.copy(dataStream, new FileOutputStream(dataFile));
        dataURL = dataFile.toURL();

    }

    File dataFile = new File(dataURL.toURI());
    File indexFile = new File(indexURL.toURI());

    if (!indexFile.exists()) {
        return null;
    }

    MTabixConfig mtabixConfig = new MTabixConfig(dataFile, indexFile, new DefaultKeyParser(1, 0));
    MTabixIndex index = new MTabixIndex(mtabixConfig);
    index.loadIndex();

    return index;

}