Adds the given file to the specified JAR file. - Java Reflection

Java examples for Reflection:Jar

Description

Adds the given file to the specified JAR file.

Demo Code

/*//from www .j a  v a2s . c  om
 * Copyright @ 2006-2010 by The Jxva Framework Foundation
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.CRC32;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class Main{
    /**
     * Adds the given file to the specified JAR file.
     * 
     * @param file the file that should be added
     * @param jarFile The JAR to which the file should be added
     * @param parentDir the parent directory of the file, this is used to calculate the path witin the JAR file.
     *                  When null is given, the file will be added into the root of the JAR.
     * @param compress True when the jar file should be compressed
     * @throws FileNotFoundException when the jarFile does not exist
     * @throws IOException when a file could not be written or the jar-file could not read.
     */
    public static void addToJar(File file, File jarFile, File parentDir,
            boolean compress) throws FileNotFoundException, IOException {
        File tmpJarFile = File.createTempFile("tmp", ".jar",
                jarFile.getParentFile());
        JarOutputStream out = new JarOutputStream(new FileOutputStream(
                tmpJarFile));
        if (compress) {
            out.setLevel(ZipOutputStream.DEFLATED);
        } else {
            out.setLevel(ZipOutputStream.STORED);
        }
        // copy contents of old jar to new jar:
        JarFile inputFile = new JarFile(jarFile);
        JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
        CRC32 crc = new CRC32();
        byte[] buffer = new byte[512 * 1024];
        JarEntry entry = (JarEntry) in.getNextEntry();
        while (entry != null) {
            InputStream entryIn = inputFile.getInputStream(entry);
            add(entry, entryIn, out, crc, buffer);
            entryIn.close();
            entry = (JarEntry) in.getNextEntry();
        }
        in.close();
        inputFile.close();

        int sourceDirLength;
        if (parentDir == null) {
            sourceDirLength = file.getAbsolutePath().lastIndexOf(
                    File.separatorChar) + 1;
        } else {
            sourceDirLength = file.getAbsolutePath().lastIndexOf(
                    File.separatorChar)
                    + 1 - parentDir.getAbsolutePath().length();
        }
        addFile(file, out, crc, sourceDirLength, buffer);
        out.close();

        // remove old jar file and rename temp file to old one:
        if (jarFile.delete()) {
            if (!tmpJarFile.renameTo(jarFile)) {
                throw new IOException(
                        "Unable to rename temporary JAR file to ["
                                + jarFile.getAbsolutePath() + "].");
            }
        } else {
            throw new IOException("Unable to delete old JAR file ["
                    + jarFile.getAbsolutePath() + "].");
        }

    }
    /**
     * @param entry
     * @param in
     * @param out
     * @param crc
     * @param buffer
     * @throws IOException
     */
    private static void add(JarEntry entry, InputStream in,
            JarOutputStream out, CRC32 crc, byte[] buffer)
            throws IOException {
        out.putNextEntry(entry);
        int read;
        long size = 0;
        while ((read = in.read(buffer)) != -1) {
            crc.update(buffer, 0, read);
            out.write(buffer, 0, read);
            size += read;
        }
        entry.setCrc(crc.getValue());
        entry.setSize(size);
        in.close();
        out.closeEntry();
        crc.reset();
    }
    /**
     * Adds one file to the given jar file.
     * If the specified file is a directory, all included files will be added.
     * 
     * @param file The file which should be added
     * @param out The jar file to which the given jar file should be added
     * @param crc A helper class for the CRC32 calculation
     * @param sourceDirLength The number of chars which can be skipped from the file's path
     * @param buffer A buffer for reading the files.
     * @throws FileNotFoundException when the file was not found
     * @throws IOException when the file could not be read or not be added
     */
    private static void addFile(File file, JarOutputStream out, CRC32 crc,
            int sourceDirLength, byte[] buffer)
            throws FileNotFoundException, IOException {
        if (file.isDirectory()) {
            File[] fileNames = file.listFiles();
            for (int i = 0; i < fileNames.length; i++) {
                addFile(fileNames[i], out, crc, sourceDirLength, buffer);
            }
        } else {
            String entryName = file.getAbsolutePath().substring(
                    sourceDirLength);
            if (SystemUtil.IS_OS_WINDOWS) {
                entryName = entryName.replace('\\', '/');
            }
            JarEntry entry = new JarEntry(entryName);
            // read file:
            FileInputStream in = new FileInputStream(file);
            add(entry, in, out, crc, buffer);
        }
    }
}

Related Tutorials