You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

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

public class ClassPathHacker {

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

  public static void addFile(String s) throws IOException {
    File f = new File(s);
    addFile(f);
  }//end method

  public static void addFile(File f) throws IOException {
    addURL(f.toURL());
  }//end method


  public static void addURL(URL u) throws IOException {

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    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");
    }//end try catch

   }//end method

}//end class

The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.

Answer from Thilo on Stack Overflow
Top answer
1 of 7
48

You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

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

public class ClassPathHacker {

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

  public static void addFile(String s) throws IOException {
    File f = new File(s);
    addFile(f);
  }//end method

  public static void addFile(File f) throws IOException {
    addURL(f.toURL());
  }//end method


  public static void addURL(URL u) throws IOException {

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    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");
    }//end try catch

   }//end method

}//end class

The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.

2 of 7
44

Try this one on for size.

private static void addSoftwareLibrary(File file) throws Exception {
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
    method.setAccessible(true);
    method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
}

This edits the system class loader to include the given library jar. It is pretty ugly, but it works.

🌐
JVM Gaming
jvm-gaming.org › newbie & debugging questions
Adding resources to the class path at run time... - Newbie & Debugging Questions - JVM Gaming
July 20, 2005 - I have made a little utility which wraps a given JAR file in a Bzip2 compression wrapper giving smaller JAR file sizes while keeping the same functionality. It can be downloaded here: http://www.geocities.com/budgetanime/bJAR.html It currently performs as excpected with Executable JARs.
🌐
Crunchify
crunchify.com › technology & tools › how to add resources folder, properties at runtime into intellij classpath? adding property files to classpath
How to add Resources Folder, Properties at Runtime into IntelliJ classpath? Adding Property files to Classpath • Crunchify
May 31, 2023 - String propFileName = "config.properties"; InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); prop.load(inputStream); <========= NPE here while loading config.properties file if (inputStream == null) { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } ... Observe result and you won’t see NullPointerException any more. I hope this simple tips will help you fix NPE and easy for you to add any resources into your Java or J2EE project at runtime without any issue.
🌐
GitHub
gist.github.com › 0338424508496b6e171e
add new class path at runtime in java · GitHub
For example adding jar to classpath, but depends on configuration or some logic at runtime. The class who responsible for handling classpath list is URLClassloader. You can get current system URLClassLoader with: URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); If you check javadoc about this class you’ll see: protected void addURL(URL url) : Appends the specified URL to the list of URLs to search for classes and resources.
🌐
ERP Great
erpgreat.com › java › add-a-file-to-java-classpath-at-runtime.htm
Add a File To Java Classpath At Runtime
My code accepts a zip file as input. I unpack several images from the zip file into a temp directory (literally, created by File.createTempFile()) · I have another program that will load these images as resources and put them into the database *if* I can get the temp directory onto the class path.
Top answer
1 of 3
15
  1. Adding resource folder to classpath:

    When you Clean-&-Build a NetBeans Ant Based Project it creates a manifest.mf file in the root directory of the project. This file gets included in the JAR file also. Modify this file and add entry like follows:

    Manifest-Version: 1.0
    X-COMMENT: Main-Class will be added automatically by build
    Class-Path: arts/  
    

    slash is important after arts in the class path.

  2. Including the arts resource folder in the distribution

    Either copy this folder in the dist folder after the build or add a ANT target to copy the required resources in the dist folder.

    Add the target like as follows in the build.xml file:

    <target name="-post-jar">
         <mkdir dir="${dist.dir}/resources"/>
         <copy todir="${dist.dir}/resources">
             <fileset dir="${basedir}/resources" />
         </copy>
     </target>
    
  3. Code to access such resources:

    The code needed to access such resource files shall be as follows: (This will not work in design time but surely from the JAR file)

    // pay attention to relative path
    URL resource = ClassLoader.getSystemResource("gui/refresh.png"); 
    ImageIcon tmp = new ImageIcon(resource);
    

    NOTE: The files manifest.mf and build.xml located in the root directory of the project are accessible from the Files Panel in NetBeans IDE

2 of 3
11

Using NetBeans 8.0.2:

  1. Right-click the project.
  2. Select Properties.
  3. Select Sources.
  4. Click Add Folder for the Source Package Folders.
  5. Select the the directory where the resources exist.
  6. Click Open on the directory name.
  7. Click OK to close the Project Properties dialog.

The resources are added to the project.

You'll see the directory added in your Navigation pane as well

In the other project, the resources are now available. For example, to read an image:

BufferedImage zero = ImageIO.read(OCR.class.getResourceAsStream("/0.bmp"));
🌐
DevTut
devtut.github.io › java › resources-on-classpath.html
Java - Resources (on classpath)
There is no safe way to list resources at runtime. Again, since the developers are responsible for adding resource files to the application at build time, developers should already know their paths.
🌐
Coderanch
coderanch.com › t › 384068 › java › Adding-JAR-file-Classpath-Runtime
Adding JAR file to Classpath at Runtime (Java in General forum at Coderanch)
November 20, 2007 - You can do this using URLClassLoader, you can get a handle to this through the static getSystemClassLoader() in the ClassLoader class. then add the jar file that you want as a URL and then load that class. ... I'd be interested in an example of that because I don't see how to do it.
🌐
Rip Tutorial
riptutorial.com › resources (on classpath)
Java Language Tutorial => Resources (on classpath)
This is not predictable behavior in environments where the classpath order is not under the direct control of the application, such as Java EE. All getResource and getResourceAsStream methods return null if the specified resource does not exist. Since resources must be added to the application at build time, their locations should be known when the code is being written; a failure to find a resource at runtime ...
Find elsewhere
🌐
Google Groups
groups.google.com › g › comp.lang.java.programmer › c › sALT2nrohQg
Load jar into classpath and access resources in it at runtime
June 21, 2022 - Alternatives to all of the above include: - at or before build time, extracting the files you need from the JAR and putting them in your /src tree flat; - putting the JAR file alongside your source tree (in a lib directory) and making sure it's added to the classpath when the runtime is launched, ...
🌐
LogicBig
logicbig.com › how-to › java › different-ways-to-load-resources.html
What are different ways to load classpath resources in Java?
November 4, 2018 - [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building load-resource 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- exec-maven-plugin:1.4.0:java (default-cli) @ load-resource --- ----------------------------------------- using this.getClass().getResource ----------------------------------------- -> attempting input resource: test-pkg-resource.txt no resource found: test-pkg-resource.txt -> attempting input resource: /test-pkg-resource.txt absolute resource path found : C:/load-resour
🌐
Gradle
discuss.gradle.org › help/discuss
Adding a resource directory to the runtime class path and excluding it from the jar - Help/Discuss - Gradle Forums
December 12, 2024 - Greetings. I have a Java/Spring Boot project where I need to decrypt some sops encrypted .env files when the app starts up. The encrypted files are checked into the BitBucket repo, and I need to 1) use the Java class path to find the appropriate file, 2) decrypt it when the app starts using a fixed directory structure/naming convention, and 3) make sure that neither the encrypted or decrypted files are part of the Jar file that gets built in the project.
🌐
Blogger
javarevisited.blogspot.com › 2014 › 07 › how-to-load-resources-from-classpath-in-java-example.html
How to Load Resources from Classpath in Java with Example
Exception in thread "main" java.lang.NullPointerException at java.util.Properties$LineReader.readLine(Unknown Source) at java.util.Properties.load0(Unknown Source) at java.util.Properties.load(Unknown Source) at Test.main(Test.java:29) to avoid this error you must check the output of getResourceAsStream() before using it, defensive programming is there just because of this kind of method. Here is our complete Java program to load images, resources, configuration files, property files, text files, or binary files from classpath in Java, Resources can be anything, what is important is that they must be accessible.
🌐
TutorialsPoint
tutorialspoint.com › loading-resources-from-classpath-in-java-with-example
Loading Resources from classpath in Java with Example
July 28, 2023 - However, do note that making use of getResourceAsStream() will get you an InputStream type return value - this must first be changed into a byte array before being converted later with String(byte[], Charset) constructor. This approach involves using getResource() method.The following is a ...
🌐
Baptiste-wicht
baptiste-wicht.com › posts › 2010 › 05 › tip-add-resources-dynamically-to-a-classloader.html
Tip : Add resources dynamically to a ClassLoader | Blog blog("Baptiste Wicht");
May 15, 2010 - Theoretically, it's not possible to ad resources to a ClassLoader in Java after creation. I say theoretically, because, we can do that using Reflection. In fact, the URLClassLoader class has a addUrl
🌐
Pretagteam
pretagteam.com › question › how-to-add-resources-to-classpath
How to add resources to classpath - Pretag
October 27, 2021 - In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath.,Click Add Folder fo...