Example usage for java.util.jar JarInputStream read

List of usage examples for java.util.jar JarInputStream read

Introduction

In this page you can find the example usage for java.util.jar JarInputStream read.

Prototype

public int read(byte[] b, int off, int len) throws IOException 

Source Link

Document

Reads from the current JAR file entry into an array of bytes.

Usage

From source file:net.ftb.util.FileUtils.java

/**
 * deletes the META-INF/*from  ww  w .  j  a v a  2  s .  c  o  m*/
 */
public static void killMetaInf() {
    File inputFile = new File(Settings.getSettings().getInstallPath() + "/" + ModPack.getSelectedPack().getDir()
            + "/minecraft/bin", "minecraft.jar");
    File outputTmpFile = new File(Settings.getSettings().getInstallPath() + "/"
            + ModPack.getSelectedPack().getDir() + "/minecraft/bin", "minecraft.jar.tmp");
    try {
        JarInputStream input = new JarInputStream(new FileInputStream(inputFile));
        JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile));
        JarEntry entry;

        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().contains("META-INF")) {
                continue;
            }
            output.putNextEntry(entry);
            byte buffer[] = new byte[1024];
            int amo;
            while ((amo = input.read(buffer, 0, 1024)) != -1) {
                output.write(buffer, 0, amo);
            }
            output.closeEntry();
        }

        input.close();
        output.close();

        if (!inputFile.delete()) {
            Logger.logError("Failed to delete Minecraft.jar.");
            return;
        }
        outputTmpFile.renameTo(inputFile);
    } catch (FileNotFoundException e) {
        Logger.logError("Error while killing META-INF", e);
    } catch (IOException e) {
        Logger.logError("Error while killing META-INF", e);
    }
}

From source file:JarUtils.java

public static void unjar(InputStream in, File dest) throws IOException {
    if (!dest.exists()) {
        dest.mkdirs();/* w  w  w .ja va2  s.c o  m*/
    }
    if (!dest.isDirectory()) {
        throw new IOException("Destination must be a directory.");
    }
    JarInputStream jin = new JarInputStream(in);
    byte[] buffer = new byte[1024];

    ZipEntry entry = jin.getNextEntry();
    while (entry != null) {
        String fileName = entry.getName();
        if (fileName.charAt(fileName.length() - 1) == '/') {
            fileName = fileName.substring(0, fileName.length() - 1);
        }
        if (fileName.charAt(0) == '/') {
            fileName = fileName.substring(1);
        }
        if (File.separatorChar != '/') {
            fileName = fileName.replace('/', File.separatorChar);
        }
        File file = new File(dest, fileName);
        if (entry.isDirectory()) {
            // make sure the directory exists
            file.mkdirs();
            jin.closeEntry();
        } else {
            // make sure the directory exists
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            // dump the file
            OutputStream out = new FileOutputStream(file);
            int len = 0;
            while ((len = jin.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            jin.closeEntry();
            file.setLastModified(entry.getTime());
        }
        entry = jin.getNextEntry();
    }
    /* Explicity write out the META-INF/MANIFEST.MF so that any headers such
    as the Class-Path are see for the unpackaged jar
    */
    Manifest mf = jin.getManifest();
    if (mf != null) {
        File file = new File(dest, "META-INF/MANIFEST.MF");
        File parent = file.getParentFile();
        if (parent.exists() == false) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(file);
        mf.write(out);
        out.flush();
        out.close();
    }
    jin.close();
}

From source file:org.ngrinder.common.util.CompressionUtil.java

/**
 * Unpack the given jar file.//from  ww w  . j av  a  2 s. c om
 * 
 * @param jarFile
 *            file to be uncompressed
 * @param destDir
 *            destination directory
 * @throws IOException
 *             occurs when IO has a problem.
 */
public static void unjar(File jarFile, String destDir) throws IOException {
    File dest = new File(destDir);
    if (!dest.exists()) {
        dest.mkdirs();
    }
    if (!dest.isDirectory()) {
        LOGGER.error("Destination must be a directory.");
        throw new IOException("Destination must be a directory.");
    }
    JarInputStream jin = new JarInputStream(new FileInputStream(jarFile));
    byte[] buffer = new byte[1024];

    ZipEntry entry = jin.getNextEntry();
    while (entry != null) {
        String fileName = entry.getName();
        if (fileName.charAt(fileName.length() - 1) == '/') {
            fileName = fileName.substring(0, fileName.length() - 1);
        }
        if (fileName.charAt(0) == '/') {
            fileName = fileName.substring(1);
        }
        if (File.separatorChar != '/') {
            fileName = fileName.replace('/', File.separatorChar);
        }
        File file = new File(dest, fileName);
        if (entry.isDirectory()) {
            // make sure the directory exists
            file.mkdirs();
            jin.closeEntry();
        } else {
            // make sure the directory exists
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            // dump the file
            OutputStream out = new FileOutputStream(file);
            int len = 0;
            while ((len = jin.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            IOUtils.closeQuietly(out);
            jin.closeEntry();
            file.setLastModified(entry.getTime());
        }
        entry = jin.getNextEntry();
    }
    Manifest mf = jin.getManifest();
    if (mf != null) {
        File file = new File(dest, "META-INF/MANIFEST.MF");
        File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(file);
        mf.write(out);
        out.flush();
        IOUtils.closeQuietly(out);
    }
    IOUtils.closeQuietly(jin);
}

From source file:JarHelper.java

/**
 * Given an InputStream on a jar file, unjars the contents into the given
 * directory./* www .  ja v a  2 s .com*/
 */
public void unjar(InputStream in, File destDir) throws IOException {
    BufferedOutputStream dest = null;
    JarInputStream jis = new JarInputStream(in);
    JarEntry entry;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (entry.isDirectory()) {
            File dir = new File(destDir, entry.getName());
            dir.mkdir();
            if (entry.getTime() != -1)
                dir.setLastModified(entry.getTime());
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER_SIZE];
        File destFile = new File(destDir, entry.getName());
        if (mVerbose)
            System.out.println("unjarring " + destFile + " from " + entry.getName());
        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        if (entry.getTime() != -1)
            destFile.setLastModified(entry.getTime());
    }
    jis.close();
}

From source file:gov.nih.nci.restgen.util.JarHelper.java

/**
 * Given an InputStream on a jar file, unjars the contents into the given
 * directory./*from   www . ja  va  2 s. c om*/
 */
public void unjar(InputStream in, File destDir) throws IOException {
    BufferedOutputStream dest = null;
    JarInputStream jis = new JarInputStream(in);
    JarEntry entry;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (entry.isDirectory()) {
            File dir = new File(destDir, entry.getName());
            dir.mkdir();
            if (entry.getTime() != -1)
                dir.setLastModified(entry.getTime());
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER_SIZE];
        File destFile = new File(destDir, entry.getName());
        if (mVerbose) {
            //System.out.println("unjarring " + destFile + " from " + entry.getName());
        }
        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        if (entry.getTime() != -1)
            destFile.setLastModified(entry.getTime());
    }
    jis.close();
}

From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java

private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) {
    try {/*from  w ww.  j a v  a  2 s .  c o  m*/
        final boolean oldExists = moveJarToOld();
        if (javacresult.size() > 0) {
            final Set<String> entries = new HashSet<String>();
            final JarOutputStream jos = new JarOutputStream(
                    new BufferedOutputStream(new FileOutputStream(JARFILE)), getManifest());

            try {
                for (final String key : javacresult.keySet()) {
                    entries.add(key);
                    byte[] bytecode = javacresult.get(key);

                    // create entry for directory (required for classpath scanning)
                    if (key.contains("/")) {
                        String dir = key.substring(0, key.lastIndexOf('/') + 1);
                        if (!entries.contains(dir)) {
                            entries.add(dir);
                            jos.putNextEntry(new JarEntry(dir));
                            jos.closeEntry();
                        }
                    }

                    // call postCompile() (weaving) on compiled sources
                    for (CodeGenerator generator : generators) {
                        if (!oldExists || generator.isRecompileNecessary()) {
                            for (JavaSourceAsString src : generator.getSourceFiles()) {
                                final String name = src.getFQName();
                                if (key.startsWith(name.replaceAll("\\.", "/"))) {
                                    LOG.debug("postCompile (weaving) " + key);
                                    bytecode = generator.postCompile(key, bytecode);
                                    // Can we break here???
                                    // break outer;
                                }
                            }
                        }
                    }
                    jos.putNextEntry(new ZipEntry(key));
                    LOG.debug("writing to " + key + " to jar " + JARFILE);
                    jos.write(bytecode);
                    jos.closeEntry();
                }

                if (oldExists) {
                    final JarInputStream in = new JarInputStream(
                            new BufferedInputStream(new FileInputStream(JARFILE_OLD)));
                    final byte[] buffer = new byte[2048];
                    try {
                        int size;
                        JarEntry entry;
                        while ((entry = in.getNextJarEntry()) != null) {
                            if (!entries.contains(entry.getName())) {
                                jos.putNextEntry(entry);
                                LOG.debug("copying " + entry.getName() + " from old jar " + JARFILE_OLD);
                                while ((size = in.read(buffer, 0, buffer.length)) != -1) {
                                    jos.write(buffer, 0, size);
                                }
                                jos.closeEntry();
                            }
                            in.closeEntry();
                        }
                    } finally {
                        in.close();
                    }
                }
            } finally {
                jos.close();
            }
        }
    } catch (IOException ex) {
        throw new NuclosFatalException(ex);
    }
}

From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java

/**
 * Extracts the project files to the project directory.
 *//*from  ww  w .  j a  v  a2 s  .c o  m*/
private void extract(URL url) throws Exception {
    packageDirs = packageName.replaceAll("\\.", "/");
    String puTemplate = DIR_TEMPLATES + "/" + template + "/";
    int length = puTemplate.length() - 1;
    BufferedInputStream bis = new BufferedInputStream(url.openStream());
    JarInputStream jis = new JarInputStream(bis);
    JarEntry je;
    byte[] buf = new byte[1024];
    int n;
    while ((je = jis.getNextJarEntry()) != null) {
        String jarEntryName = je.getName();
        PluginLog.getLog().debug("JAR entry: " + jarEntryName);
        if (je.isDirectory() || !jarEntryName.startsWith(puTemplate)) {
            continue;
        }
        String targetFileName = projectDir + jarEntryName.substring(length);

        // convert the ${gsGroupPath} to directory
        targetFileName = StringUtils.replace(targetFileName, FILTER_GROUP_PATH, packageDirs);
        PluginLog.getLog().debug("Extracting entry " + jarEntryName + " to " + targetFileName);

        // read the bytes to the buffer
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        while ((n = jis.read(buf, 0, 1024)) > -1) {
            byteStream.write(buf, 0, n);
        }

        // replace property references with the syntax ${property_name}
        // to their respective property values.
        String data = byteStream.toString();
        data = StringUtils.replace(data, FILTER_GROUP_ID, packageName);
        data = StringUtils.replace(data, FILTER_ARTIFACT_ID, projectDir.getName());
        data = StringUtils.replace(data, FILTER_GROUP_PATH, packageDirs);

        // write the entire converted file content to the destination file.
        File f = new File(targetFileName);
        File dir = f.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileWriter writer = new FileWriter(f);
        writer.write(data);
        jis.closeEntry();
        writer.close();
    }
    jis.close();
}

From source file:com.paniclauncher.workers.InstanceInstaller.java

public void deleteMetaInf() {
    File inputFile = getMinecraftJar();
    File outputTmpFile = new File(App.settings.getTempDir(), pack.getSafeName() + "-minecraft.jar");
    try {//from  w w w.j  a  v a  2  s  .co m
        JarInputStream input = new JarInputStream(new FileInputStream(inputFile));
        JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile));
        JarEntry entry;

        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().contains("META-INF")) {
                continue;
            }
            output.putNextEntry(entry);
            byte buffer[] = new byte[1024];
            int amo;
            while ((amo = input.read(buffer, 0, 1024)) != -1) {
                output.write(buffer, 0, amo);
            }
            output.closeEntry();
        }

        input.close();
        output.close();

        inputFile.delete();
        outputTmpFile.renameTo(inputFile);
    } catch (IOException e) {
        App.settings.getConsole().logStackTrace(e);
    }
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * Reads the content of a given entry in a Jar file (JarInputStream) and returns it as a String
 *
 * @param jarStream the given JarInputStream
 * @param entry     the given entry in the jar file
 * @return the entry's content as a String
 * @throws java.io.IOException on errors
 *//*  ww w  .j  a  v  a2 s  .  com*/
public static String readFromJarEntry(JarInputStream jarStream, JarEntry entry) throws IOException {
    final String fileContent;
    if (entry.getSize() >= 0) {
        // allocate buffer for the entire (uncompressed) script code
        final byte[] buffer = new byte[(int) entry.getSize()];
        // decompress JAR entry
        int offset = 0;
        int readBytes;
        while ((readBytes = jarStream.read(buffer, offset, (int) entry.getSize() - offset)) > 0) {
            offset += readBytes;
        }
        if (offset != entry.getSize()) {
            throw new IOException("Failed to read complete script code for script: " + entry.getName());
        }
        fileContent = new String(buffer, "UTF-8").trim();
    } else {
        // use this method if the file size cannot be determined
        //(might be the case with jar files created with some jar tools)
        final StringBuilder out = new StringBuilder();
        final byte[] buf = new byte[1024];
        int readBytes;
        while ((readBytes = jarStream.read(buf, 0, buf.length)) > 0) {
            out.append(new String(buf, 0, readBytes, "UTF-8"));
        }
        fileContent = out.toString();
    }
    return fileContent;
}

From source file:com.amalto.workbench.utils.Util.java

public static ByteArrayOutputStream retrieveJarEntryAsBytes(File barFile, String entryName) {
    JarInputStream jarIn = null;
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream();

    try {/*from   w  ww  .j  av a  2 s .co  m*/
        jarIn = new JarInputStream(new FileInputStream(barFile));
        JarEntry entry;
        byte[] buf = new byte[4096];
        while ((entry = jarIn.getNextJarEntry()) != null) {
            if (entry.toString().equals(entryName)) {
                int read;
                while ((read = jarIn.read(buf, 0, 4096)) != -1) {
                    outBytes.write(buf, 0, read);
                }
                if (outBytes.toByteArray().length > 0) {
                    return outBytes;
                }
            }
        }
    } catch (Exception e) {
    }
    return null;
}