Java ClassLoader addFile(String s)

Here you can find the source of addFile(String s)

Description

Add file to CLASSPATH

License

Open Source License

Parameter

Parameter Description
s File name

Exception

Parameter Description
IOExceptionIOException

Declaration


public static void addFile(String s) throws IOException 

Method Source Code


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

import java.io.File;
import java.io.IOException;
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  .  j  a v a2  s. c o  m*/
        
     * Add file to CLASSPATH
        
     * @param s File name
        
     * @throws IOException  IOException
        
     */

    public static void addFile(String s) throws IOException {

        File f = new File(s);

        addFile(f);

    }

    /**
        
     * Add file to CLASSPATH
        
     * @param f  File object
        
     * @throws IOException IOException
        
     */

    public static void addFile(File f) throws IOException {

        addURL(f.toURL());

    }

    /**
        
     * 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())) {
                return;
            }

        }

        Class sysclass = URLClassLoader.class;

        try {

            Method method = sysclass.getDeclaredMethod("addURL", parameters);

            method.setAccessible(true);

            method.invoke(sysLoader, new Object[] { u });

        } catch (Throwable t) {

            t.printStackTrace();

            throw new IOException("Error, could not add URL to system classloader");

        }

    }
}

Related

  1. add(File file)
  2. addDirectory(File directory)
  3. AddFile(File f)
  4. addFile(File file)
  5. createDir(String pathName)
  6. createDirectoryLoader(String directory)
  7. CreateLogbackXML(OutputStream out)
  8. findFile(String filename)