集册 Java实例教程 将给定目录中的jar添加到classpath

将给定目录中的jar添加到classpath

欢马劈雪     最近更新时间:2020-01-02 10:19:05

508
将给定目录中的jar添加到classpath

/*

 * Copyright (C) 2012 Dr. John Lindsay <jlindsay@uoguelph.ca>

 *

 * This program is free software: you can redistribute it and/or modify

 * it under the terms of the GNU General Public License as published by

 * the Free Software Foundation, either version 3 of the License, or

 * (at your option) any later version.

 *

 * This program is distributed in the hope that it will be useful,

 * but WITHOUT ANY WARRANTY; without even the implied warranty of

 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

 * GNU General Public License for more details.

 *

 * You should have received a copy of the GNU General Public License

 * along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

//package com.nowjava;/** from nowjava.com - 时  代  Java**/

import java.io.File;

import java.io.IOException;

import java.lang.reflect.Method;

import java.net.URL;

import java.net.URLClassLoader;


public class Main {

    public static void main(String[] argv) throws Exception {

        File directory = new File("Main.java");

        addDirToClasspath(directory);

    }


    private static final Class[] parameters = new Class[] { URL.class };


    /**

     * Adds the jars in the given directory to classpath

     * @param directory

     * @throws IOException

     */

    public static void addDirToClasspath(File directory) throws IOException {

        if (directory.exists()) {

            File[] files = directory.listFiles();

            for (int i = 0; i < files.length; i++) {
            /* from 
            时 代 J a v a 公 众 号*/

                File file = files[i];

                addURL(file.toURI().toURL());

            }

        } else {

            System.err.println("The directory \"" + directory

                    + "\" does not exist!");

        }

    }


    /**

     * Add URL to CLASSPATH

     * @param u URL

     * @throws IOException IOException

     */

    public static void addURL(URL u) throws IOException {

        URLClassLoader sysLoader = (URLClassLoader) ClassLoader

                .getSystemClassLoader();

        URL urls[] = sysLoader.getURLs();

        for (int i = 0; i < urls.length; i++) {

            if (urls[i].toString().equalsIgnoreCase(u.toString())) {

                System.err.println("URL " + u

                        + " is already in the CLASSPATH");

                return;

            }

        }

        Class sysclass = 
展开阅读全文