Java Jar Zip File addJARs(File dir)

Here you can find the source of addJARs(File dir)

Description

Add all the jar files in a directory tree to the classpath.

License

Open Source License

Parameter

Parameter Description
dir the top-level directory in the tree

Declaration

public static void addJARs(File dir) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    private static final Class<?>[] parameters = new Class[] { URL.class };

    /**/*from w  w w  .ja v a 2  s .c om*/
     * Add all the jar files in a directory tree to the classpath.
     * @param dir the top-level directory in the tree
     */
    public static void addJARs(File dir) {
        if (dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (file.isFile()) {
                    if (file.getName().toLowerCase().endsWith(".jar") && !addFile(file)) {
                        System.out.println("Unable to add " + file + " to the classpath.");
                    }
                } else if (file.isDirectory())
                    addJARs(file);
            }
        }
    }

    /**
     * Add a file to the classpath.
     * @param file the file to add
     * @return true if the file was successfully added; false otherwise.
     */
    public static boolean addFile(File file) {
        try {
            return addURL(file.toURI().toURL());
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * Add a URL to the classpath.
     * @param url the URL to add
     * @return true if the URL was successfully added; false otherwise.
     */
    public static boolean addURL(URL url) {
        URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class<?> sysclass = URLClassLoader.class;

        try {
            Method method = sysclass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true);
            method.invoke(sysloader, new Object[] { url });
            return true;
        } catch (Throwable t) {
            return false;
        }
    }
}

Related

  1. addFileToJar(File fileOrDirectoryToAdd, File extractedJarPath, JarOutputStream target)
  2. addFileToJar(JarOutputStream jar, InputStream file, String path)
  3. addJar(File path)
  4. addJarLibralyClassPath(Object classLoaderMakedObject, File jarPath)
  5. addJarLibralySystemClassPath(File jarPath)
  6. addJars(File directory, boolean recursive)
  7. addJarsToClassPath(String jarPath)
  8. addJarToClasspath(File jarFile)
  9. addToJar(File source, JarOutputStream jarOutput)