Example usage for java.util.jar JarOutputStream putNextEntry

List of usage examples for java.util.jar JarOutputStream putNextEntry

Introduction

In this page you can find the example usage for java.util.jar JarOutputStream putNextEntry.

Prototype

public void putNextEntry(ZipEntry ze) throws IOException 

Source Link

Document

Begins writing a new JAR file entry and positions the stream to the start of the entry data.

Usage

From source file:com.cloudera.sqoop.orm.CompilationManager.java

/**
 * Searches through a directory and its children for .class
 * files to add to a jar./* w  w  w .j a  v a2s. c o  m*/
 *
 * @param dir - The root directory to scan with this algorithm.
 * @param jstream - The JarOutputStream to write .class files to.
 */
private void addClassFilesFromDir(File dir, JarOutputStream jstream) throws IOException {
    LOG.debug("Scanning for .class files in directory: " + dir);
    List<File> dirEntries = FileListing.getFileListing(dir);
    String baseDirName = dir.getAbsolutePath();
    if (!baseDirName.endsWith(File.separator)) {
        baseDirName = baseDirName + File.separator;
    }

    // For each input class file, create a zipfile entry for it,
    // read the file into a buffer, and write it to the jar file.
    for (File entry : dirEntries) {
        if (!entry.isDirectory()) {
            // Chomp off the portion of the full path that is shared
            // with the base directory where class files were put;
            // we only record the subdir parts in the zip entry.
            String fullPath = entry.getAbsolutePath();
            String chompedPath = fullPath.substring(baseDirName.length());

            boolean include = chompedPath.endsWith(".class") && sources
                    .contains(chompedPath.substring(0, chompedPath.length() - ".class".length()) + ".java");

            if (include) {
                // include this file.
                LOG.debug("Got classfile: " + entry.getPath() + " -> " + chompedPath);
                ZipEntry ze = new ZipEntry(chompedPath);
                jstream.putNextEntry(ze);
                copyFileToStream(entry, jstream);
                jstream.closeEntry();
            }
        }
    }
}

From source file:com.taobao.android.tools.TPatchTool.java

/**
 * Adds a directory to a {@link} with a directory prefix.
 *
 * @param jos       ZipArchiver to use to archive the file.
 * @param directory The directory to add.
 * @param prefix    An optional prefix for where in the Jar file the directory's contents should go.
 *///from   ww w.j  av  a  2  s  .com
protected void addDirectory(JarOutputStream jos, File directory, String prefix) throws IOException {
    if (directory != null && directory.exists()) {
        Collection<File> files = FileUtils.listFiles(directory, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        byte[] buf = new byte[8064];
        for (File file : files) {
            if (file.isDirectory()) {
                continue;
            }
            String path = prefix + "/" + PathUtils.toRelative(directory, file.getAbsolutePath());
            InputStream in = null;
            try {
                in = new FileInputStream(file);
                ZipEntry fileEntry = new ZipEntry(path);
                jos.putNextEntry(fileEntry);
                // Transfer bytes from the file to the ZIP file
                int len;
                while ((len = in.read(buf)) > 0) {
                    jos.write(buf, 0, len);
                }
                // Complete the entry
                jos.closeEntry();
                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    }
}

From source file:org.echocat.nodoodle.transport.HandlerUnpacker.java

protected SplitResult splitMultipleJarIntoJars(InputStream inputStream, File targetDirectory)
        throws IOException {
    if (inputStream == null) {
        throw new NullPointerException();
    }/*from ww  w  . j a va 2  s.  co m*/
    if (targetDirectory == null) {
        throw new NullPointerException();
    }
    final Collection<File> jarFiles = new ArrayList<File>();
    final File mainJarFile = getMainJarFile(targetDirectory);
    jarFiles.add(mainJarFile);
    final JarInputStream jarInput = new JarInputStream(inputStream);
    final Manifest manifest = jarInput.getManifest();
    final FileOutputStream mainJarFileStream = new FileOutputStream(mainJarFile);
    try {
        final JarOutputStream jarOutput = new JarOutputStream(mainJarFileStream, manifest);
        try {
            JarEntry entry = jarInput.getNextJarEntry();
            while (entry != null) {
                final String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.startsWith("lib/")) {
                    final File targetFile = new File(targetDirectory, entryName);
                    if (!targetFile.getParentFile().mkdirs()) {
                        throw new IOException("Could not create parent directory of " + targetFile + ".");
                    }
                    final OutputStream outputStream = new FileOutputStream(targetFile);
                    try {
                        IOUtils.copy(jarInput, outputStream);
                    } finally {
                        IOUtils.closeQuietly(outputStream);
                    }
                    jarFiles.add(targetFile);
                } else {
                    if (entryName.startsWith(TransportConstants.CLASSES_PREFIX)
                            && entryName.length() > TransportConstants.CLASSES_PREFIX.length()) {
                        try {
                            ZIP_ENTRY_NAME_FIELD.set(entry, entryName.substring(CLASSES_PREFIX.length()));
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException("Could not set " + ZIP_ENTRY_NAME_FIELD + ".", e);
                        }
                    }
                    jarOutput.putNextEntry(entry);
                    IOUtils.copy(jarInput, jarOutput);
                    jarOutput.closeEntry();
                }
                entry = jarInput.getNextJarEntry();
            }
        } finally {
            IOUtils.closeQuietly(jarOutput);
        }
    } finally {
        IOUtils.closeQuietly(mainJarFileStream);
    }
    return new SplitResult(Collections.unmodifiableCollection(jarFiles), manifest);
}

From source file:org.apache.hadoop.sqoop.orm.CompilationManager.java

/**
 * Create an output jar file to use when executing MapReduce jobs
 *//*from  w  w w .  ja va2 s .  co  m*/
public void jar() throws IOException {
    String jarOutDir = options.getJarOutputDir();
    List<File> outDirEntries = FileListing.getFileListing(new File(jarOutDir));

    String jarFilename = getJarFilename();

    LOG.info("Writing jar file: " + jarFilename);

    findThisJar();
    File jarFileObj = new File(jarFilename);
    if (jarFileObj.exists()) {
        if (!jarFileObj.delete()) {
            LOG.warn("Could not remove existing jar file: " + jarFilename);
        }
    }

    FileOutputStream fstream = null;
    JarOutputStream jstream = null;
    try {
        fstream = new FileOutputStream(jarFilename);
        jstream = new JarOutputStream(fstream);

        // for each input class file, create a zipfile entry for it,
        // read the file into a buffer, and write it to the jar file.

        for (File entry : outDirEntries) {
            if (entry.equals(jarFileObj)) {
                // don't include our own jar!
                continue;
            } else if (entry.isDirectory()) {
                // don't write entries for directories
                continue;
            } else {
                String fileName = entry.getName();

                boolean include = fileName.endsWith(".class") && sources
                        .contains(fileName.substring(0, fileName.length() - ".class".length()) + ".java");

                if (include) {
                    // include this file.

                    // chomp off the portion of the full path that is shared
                    // with the base directory where class files were put;
                    // we only record the subdir parts in the zip entry.
                    String fullPath = entry.getAbsolutePath();
                    String chompedPath = fullPath.substring(jarOutDir.length());

                    LOG.debug("Got classfile: " + entry.getPath() + " -> " + chompedPath);
                    ZipEntry ze = new ZipEntry(chompedPath);
                    jstream.putNextEntry(ze);
                    copyFileToStream(entry, jstream);
                    jstream.closeEntry();
                }
            }
        }

        // put our own jar in there in its lib/ subdir
        String thisJarFile = findThisJar();
        if (null != thisJarFile) {
            File thisJarFileObj = new File(thisJarFile);
            String thisJarBasename = thisJarFileObj.getName();
            String thisJarEntryName = "lib" + File.separator + thisJarBasename;
            ZipEntry ze = new ZipEntry(thisJarEntryName);
            jstream.putNextEntry(ze);
            copyFileToStream(thisJarFileObj, jstream);
            jstream.closeEntry();
        } else {
            // couldn't find our own jar (we were running from .class files?)
            LOG.warn("Could not find jar for Sqoop; MapReduce jobs may not run correctly.");
        }
    } finally {
        IOUtils.closeStream(jstream);
        IOUtils.closeStream(fstream);
    }
}

From source file:org.gradle.jvm.tasks.api.ApiJar.java

@TaskAction
public void createApiJar() throws IOException {
    // Make sure all entries are always written in the same order
    final File[] sourceFiles = sortedSourceFiles();
    final ApiClassExtractor apiClassExtractor = new ApiClassExtractor(getExportedPackages());
    withResource(new JarOutputStream(new BufferedOutputStream(new FileOutputStream(getOutputFile()), 65536)),
            new ErroringAction<JarOutputStream>() {
                @Override/*  w  ww . j  ava  2s .  c  om*/
                protected void doExecute(final JarOutputStream jos) throws Exception {
                    writeManifest(jos);
                    writeClasses(jos);
                }

                private void writeManifest(JarOutputStream jos) throws IOException {
                    writeEntry(jos, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes());
                }

                private void writeClasses(JarOutputStream jos) throws Exception {
                    for (File sourceFile : sourceFiles) {
                        if (!isClassFile(sourceFile)) {
                            continue;
                        }
                        ClassReader classReader = new ClassReader(readFileToByteArray(sourceFile));
                        if (!apiClassExtractor.shouldExtractApiClassFrom(classReader)) {
                            continue;
                        }

                        byte[] apiClassBytes = apiClassExtractor.extractApiClassFrom(classReader);
                        String internalClassName = classReader.getClassName();
                        String entryPath = internalClassName + ".class";
                        writeEntry(jos, entryPath, apiClassBytes);
                    }
                }

                private void writeEntry(JarOutputStream jos, String name, byte[] bytes) throws IOException {
                    JarEntry je = new JarEntry(name);
                    // Setting time to 0 because we need API jars to be identical independently of
                    // the timestamps of class files
                    je.setTime(0);
                    je.setSize(bytes.length);
                    jos.putNextEntry(je);
                    jos.write(bytes);
                    jos.closeEntry();
                }
            });
}

From source file:org.apache.sling.osgi.obr.Repository.java

File spoolModified(InputStream ins) throws IOException {
    JarInputStream jis = new JarInputStream(ins);

    // immediately handle the manifest
    JarOutputStream jos;
    Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Missing Manifest !");
    }/*from  w w  w  .j a  v  a  2 s  . co  m*/

    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    if (symbolicName == null || symbolicName.length() == 0) {
        throw new IOException("Missing Symbolic Name in Manifest !");
    }

    String version = manifest.getMainAttributes().getValue("Bundle-Version");
    Version v = Version.parseVersion(version);
    if (v.getQualifier().indexOf("SNAPSHOT") >= 0) {
        String tStamp;
        synchronized (DATE_FORMAT) {
            tStamp = DATE_FORMAT.format(new Date());
        }
        version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "."
                + v.getQualifier().replaceAll("SNAPSHOT", tStamp);
        manifest.getMainAttributes().putValue("Bundle-Version", version);
    }

    File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar");
    OutputStream out = null;
    try {
        out = new FileOutputStream(bundle);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                spool(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();

    } finally {
        IOUtils.closeQuietly(out);
    }

    return bundle;
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

private void compileJavaModule(File jarOutputFolder, File classesOutputFolder, String moduleName,
        String moduleVersion, File sourceFolder, File[] extraClassPath, String... sourceFileNames)
        throws IOException {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    assertNotNull("Missing Java compiler, this test is probably being run with a JRE instead of a JDK!",
            javaCompiler);/*from w w w . j  a v  a  2  s .c  o m*/
    StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
    Set<String> sourceDirectories = new HashSet<String>();
    File[] javaSourceFiles = new File[sourceFileNames.length];
    for (int i = 0; i < javaSourceFiles.length; i++) {
        javaSourceFiles[i] = new File(sourceFolder, sourceFileNames[i]);
        String sfn = sourceFileNames[i].replace(File.separatorChar, '/');
        int p = sfn.lastIndexOf('/');
        String sourceDir = sfn.substring(0, p);
        sourceDirectories.add(sourceDir);
    }
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaSourceFiles);
    StringBuilder cp = new StringBuilder();
    for (int i = 0; i < extraClassPath.length; i++) {
        if (i > 0)
            cp.append(File.pathSeparator);
        cp.append(extraClassPath[i]);
    }
    CompilationTask task = javaCompiler.getTask(null, null, null, Arrays.asList("-d",
            classesOutputFolder.getPath(), "-cp", cp.toString(), "-sourcepath", sourceFolder.getPath()), null,
            compilationUnits);
    assertEquals(Boolean.TRUE, task.call());

    File jarFolder = new File(jarOutputFolder,
            moduleName.replace('.', File.separatorChar) + File.separatorChar + moduleVersion);
    jarFolder.mkdirs();
    File jarFile = new File(jarFolder, moduleName + "-" + moduleVersion + ".jar");
    // now jar it up
    JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(jarFile));
    for (String sourceFileName : sourceFileNames) {
        String classFileName = sourceFileName.substring(0, sourceFileName.length() - 5) + ".class";
        ZipEntry entry = new ZipEntry(classFileName);
        outputStream.putNextEntry(entry);

        File classFile = new File(classesOutputFolder, classFileName);
        FileInputStream inputStream = new FileInputStream(classFile);
        Util.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.flush();
    }
    outputStream.close();
    for (String sourceDir : sourceDirectories) {
        File module = null;
        String sourceName = "module.properties";
        File properties = new File(sourceFolder, sourceDir + File.separator + sourceName);
        if (properties.exists()) {
            module = properties;
        } else {
            sourceName = "module.xml";
            properties = new File(sourceFolder, sourceDir + File.separator + sourceName);
            if (properties.exists()) {
                module = properties;
            }
        }
        if (module != null) {
            File moduleFile = new File(sourceFolder, sourceDir + File.separator + sourceName);
            FileInputStream inputStream = new FileInputStream(moduleFile);
            FileOutputStream moduleOutputStream = new FileOutputStream(new File(jarFolder, sourceName));
            Util.copy(inputStream, moduleOutputStream);
            inputStream.close();
            moduleOutputStream.flush();
            moduleOutputStream.close();
        }
    }
}

From source file:lu.fisch.moenagade.model.Project.java

public void jar() {
    try {/* w  w w .  j a  va2  s.  co  m*/
        // compile all
        if (!save())
            return;

        generateSource(true);
        if (compile()) {
            // adjust the dirname
            String bdir = getDirectoryName();
            if (!bdir.endsWith(System.getProperty("file.separator"))) {
                bdir += System.getProperty("file.separator");
            }

            // adjust the filename
            String bname = getDirectoryName();
            if (bname.endsWith(System.getProperty("file.separator"))) {
                bname = bname.substring(0, bname.length() - 1);
            }
            bname = bname.substring(bname.lastIndexOf(System.getProperty("file.separator")) + 1);

            // default class to launch
            String mc = "moenagade.Project";

            // target JVM
            String target = "1.8";

            /*
            String[] targets = new String[]{"1.1","1.2","1.3","1.5","1.6"};
            if(System.getProperty("java.version").startsWith("1.7"))
            targets = new String[]{"1.1","1.2","1.3","1.5","1.6","1.7"};
            if(System.getProperty("java.version").startsWith("1.8"))
            targets = new String[]{"1.1","1.2","1.3","1.5","1.6","1.7","1.8"};
                    
            target= (String) JOptionPane.showInputDialog(
                           frame,
                           "Please enter version of the JVM you want to target.",
                           "Target JVM",
                           JOptionPane.QUESTION_MESSAGE,
                           Moenagade.IMG_QUESTION,
                           targets,
                           "1.6");*/

            File fDir = new File(directoryName + System.getProperty("file.separator") + "bin");
            if (!fDir.exists())
                fDir.mkdir();

            // get all the files content
            Hashtable<String, String> codes = new Hashtable<>();
            String srcdir = directoryName + System.getProperty("file.separator") + "src";
            Collection files = FileUtils.listFiles(new File(srcdir), new String[] { "java" }, true);

            File[] javas = new File[files.size()];
            int i = 0;
            for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                File file = (File) iterator.next();
                javas[i++] = file;
            }

            try {
                // make class files
                Runtime6.getInstance().compileToPath(javas, fDir.getAbsolutePath(), target, "");

                StringList manifest = new StringList();
                manifest.add("Manifest-Version: 1.0");
                manifest.add("Created-By: " + Moenagade.E_VERSION + " " + Moenagade.E_VERSION);
                manifest.add("Name: " + bname);
                if (mc != null) {
                    manifest.add("Main-Class: " + mc);
                }

                // compose the filename
                fDir = new File(bdir + "dist" + System.getProperty("file.separator"));
                fDir.mkdir();
                bname = bdir + "dist" + System.getProperty("file.separator") + bname + ".jar";
                String baseName = bdir;
                String libFolderName = bdir + "lib";
                String distLibFolderName = bdir + "dist" + System.getProperty("file.separator") + "lib";

                File outFile = new File(bname);
                FileOutputStream bo = new FileOutputStream(bname);
                JarOutputStream jo = new JarOutputStream(bo);

                String dirname = getDirectoryName();
                if (!dirname.endsWith(System.getProperty("file.separator"))) {
                    dirname += System.getProperty("file.separator");
                }
                // add the files to the array
                addToJar(jo, "", new File(dirname + "bin" + System.getProperty("file.separator")));
                // add the files to the array
                addToJar(jo, "", new File(dirname + "src" + System.getProperty("file.separator")),
                        new String[] { "java" });

                //manifest.add("Class-Path: "+cp+" "+cpsw);

                // adding the manifest file
                manifest.add("");
                JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
                jo.putNextEntry(je);
                String mf = manifest.getText();
                jo.write(mf.getBytes(), 0, mf.getBytes().length);

                jo.close();
                bo.close();

                // delete bin directory
                deleteDirectory(new File(getDirectoryName() + System.getProperty("file.separator") + "bin"
                        + System.getProperty("file.separator")));
                // generate java code with dispose_on_exit
                generateSource();

                JOptionPane.showMessageDialog(frame,
                        "The JAR-archive has been generated and can\nbe found in the \"dist\" directory.",
                        "Success", JOptionPane.INFORMATION_MESSAGE, Moenagade.IMG_INFO);
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
        }
    }
    /*catch (ClassNotFoundException ex)
    {
    JOptionPane.showMessageDialog(frame, "There was an error while creating the JAR-archive ...", "Error :: ClassNotFoundException", JOptionPane.ERROR_MESSAGE,Unimozer.IMG_ERROR);
    }*/
    catch (IOException ex) {
        JOptionPane.showMessageDialog(frame, "There was an error while creating the JAR-archive ...",
                "Error :: IOException", JOptionPane.ERROR_MESSAGE, Moenagade.IMG_ERROR);
        ex.printStackTrace();
    }
}

From source file:org.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Recorre el war para escribir los archivos web.xml, la api de dspace y los jar de lucene
 *
 * @throws IOException/*from w w  w  .  j  a v a 2  s.co m*/
 * @throws TransformerException
 */
private void writeNewJar() throws IOException, TransformerException {
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.eDMExportWarJarFile.getName()).getParentFile();
    // archivo temporal del nuevo war
    File newJarFile = File.createTempFile("EDMExport", ".jar", jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura para el nuevo war
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        // recorrer los archivos del war
        Enumeration<JarEntry> entries = eDMExportWarJarFile.entries();
        // libreras de lucene
        Pattern luceneLibPattern = Pattern.compile("^WEB-INF/lib/(lucene-.+?)-\\d+.+\\.jar$");
        boolean newApiCopied = false;
        if (dspaceApi == null)
            newApiCopied = true;
        boolean replace = false;
        // recorrer
        while (entries.hasMoreElements()) {
            replace = false;
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            InputStream intputStream = null;
            // todos menos web.xml
            if (!entry.getName().equals("WEB-INF/web.xml")) {
                // api de dspace, se muestra la actual y la de dspace para pedir si se copia
                if (!newApiCopied && entry.getName().matches("^WEB-INF/lib/dspace-api-\\d+.+\\.jar$")) {
                    String response = null;
                    do {
                        installerEDMDisplay.showLn();
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace.question",
                                new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                        dspaceApi.getAbsolutePath() });
                        response = br.readLine();
                        if (response == null)
                            continue;
                        response = response.trim();
                        if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                            replace = true;
                            break;
                        } else if (response.equalsIgnoreCase("n")) {
                            break;
                        }
                    } while (true);
                    // se reemplaza por la de dspace
                    if (replace) {
                        JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + dspaceApi.getName());
                        newJarEntry.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(newJarEntry);
                        intputStream = new FileInputStream(dspaceApi);
                        newApiCopied = true;
                        if (debug) {
                            installerEDMDisplay.showLn();
                            installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                    new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                            dspaceApi.getAbsolutePath() });
                            installerEDMDisplay.showLn();
                        }
                    }
                } else {
                    // libreras de lucene
                    Matcher luceneLibMatcher = luceneLibPattern.matcher(entry.getName());
                    if (luceneLibMatcher.find()) {
                        String prefixLuceneLib = luceneLibMatcher.group(1);
                        File luceneLibFile = null;
                        String patternFile = prefixLuceneLib + "-\\d+.+\\.jar";
                        for (File file : luceneLibs) {
                            if (file.getName().matches(patternFile)) {
                                luceneLibFile = file;
                                break;
                            }
                        }
                        if (luceneLibFile != null) {
                            String response = null;
                            do {
                                installerEDMDisplay.showLn();
                                installerEDMDisplay.showQuestion(currentStepGlobal,
                                        "writeNewJar.replace.question",
                                        new String[] { entry.getName(),
                                                "WEB-INF/lib/" + luceneLibFile.getName(),
                                                luceneLibFile.getAbsolutePath() });
                                response = br.readLine();
                                if (response == null)
                                    continue;
                                response = response.trim();
                                if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                                    replace = true;
                                    break;
                                } else if (response.equalsIgnoreCase("n")) {
                                    break;
                                }
                            } while (true);
                            // se reemplaza por la de dspace
                            if (replace) {
                                JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + luceneLibFile.getName());
                                newJarEntry.setCompressedSize(-1);
                                jarOutputStream.putNextEntry(newJarEntry);
                                intputStream = new FileInputStream(luceneLibFile);
                                if (debug) {
                                    installerEDMDisplay.showLn();
                                    installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                            new String[] { entry.getName(),
                                                    "WEB-INF/lib/" + luceneLibFile.getName(),
                                                    luceneLibFile.getAbsolutePath() });
                                    installerEDMDisplay.showLn();
                                }
                            }
                        }
                        // si no era la api de dspace o las libreras de lucene se copia tal cual
                    } else if (!replace) {
                        JarEntry entryOld = new JarEntry(entry);
                        entryOld.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(entryOld);
                        intputStream = eDMExportWarJarFile.getInputStream(entry);
                    }
                }
                if (intputStream == null) {
                    if (debug)
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.notIS",
                                new String[] { entry.getName() });
                    continue;
                }
                // se lee el archivo y se copia al flujo de escritura del war
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    jarOutputStream.write(data, 0, count);
                }
                intputStream.close();
            }
        }
        installerEDMDisplay.showLn();
        // se aade web.xml al war
        addNewWebXml(jarOutputStream);
        // cerramos el archivo jar y borramos el war
        eDMExportWarJarFile.close();
        eDMExportWarWorkFile.delete();
        // sustituimos el viejo por el temporal
        try {
            /*if (newJarFile.renameTo(eDMExportWarWorkFile) && eDMExportWarWorkFile.setExecutable(true, true)) {
            eDMExportWarWorkFile = new File(myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, eDMExportWarWorkFile);
            //newJarFile.renameTo(eDMExportWarWorkFile);
            eDMExportWarWorkFile.setExecutable(true, true);
            eDMExportWarWorkFile = new File(
                    myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

From source file:lu.fisch.moenagade.model.Project.java

private void addToJar(JarOutputStream jo, String baseDir, File directory, String[] excludeExtention)
        throws FileNotFoundException, IOException {
    // get all files
    File[] files = directory.listFiles();
    for (int f = 0; f < files.length; f++) {
        if (files[f].isDirectory()) {
            String entry = files[f].getAbsolutePath();
            entry = entry.substring(directory.getAbsolutePath().length() + 1);
            addToJar(jo, baseDir + entry + "/", files[f], excludeExtention);
        } else {//from   w  w w.j  a  va 2 s  .  c o  m
            //System.out.println("File = "+files[f].getAbsolutePath());
            //System.out.println("List = "+Arrays.deepToString(excludeExtention));
            //System.out.println("We got = "+getExtension(files[f]));
            if (!Arrays.asList(excludeExtention).contains(getExtension(files[f]))) {

                FileInputStream bi = new FileInputStream(files[f]);

                String entry = files[f].getAbsolutePath();
                entry = entry.substring(directory.getAbsolutePath().length() + 1);
                entry = baseDir + entry;
                JarEntry je = new JarEntry(entry);
                jo.putNextEntry(je);
                byte[] buf = new byte[1024];
                int anz;
                while ((anz = bi.read(buf)) != -1) {
                    jo.write(buf, 0, anz);
                }
                bi.close();
            }
        }
    }
}