With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:

// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
                                .getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

If those aren't working, that suggests something else is wrong.

So for example, take this code:

package dummy;

import java.io.*;

public class Test
{
    public static void main(String[] args)
    {
        InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
        System.out.println(stream != null);
        stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
        System.out.println(stream != null);
    }
}

And this directory structure:

code
    dummy
          Test.class
txt
    SomeTextFile.txt

And then (using the Unix path separator as I'm on a Linux box):

java -classpath code:txt dummy.Test

Results:

true
true
Answer from Jon Skeet on Stack Overflow
Top answer
1 of 16
678

With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:

// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
                                .getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

If those aren't working, that suggests something else is wrong.

So for example, take this code:

package dummy;

import java.io.*;

public class Test
{
    public static void main(String[] args)
    {
        InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
        System.out.println(stream != null);
        stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
        System.out.println(stream != null);
    }
}

And this directory structure:

code
    dummy
          Test.class
txt
    SomeTextFile.txt

And then (using the Unix path separator as I'm on a Linux box):

java -classpath code:txt dummy.Test

Results:

true
true
2 of 16
137

When using the Spring Framework (either as a collection of utilities or container - you do not need to use the latter functionality) you can easily use the Resource abstraction.

Resource resource = new ClassPathResource("com/example/Foo.class");

Through the Resource interface you can access the resource as InputStream, URL, URI or File. Changing the resource type to e.g. a file system resource is a simple matter of changing the instance.

🌐
Xenovation
xenovation.com › home › blog › java › java - read file from classpath
Java - Read file from classpath | XENOVATION
April 24, 2019 - Lets say that we have created Java project called ClasspathExample and we need to read example.xml from it, firstly we need to add resource folder to classpath and then read it. package com.xenovation; import java.io.File; import java.net.URL; public class ClasspathExample { public File readFileFromClasspath() { URL fileUrl = getClass().getResource("/example.xml"); return new File(fileUrl.getFile()); } }
Discussions

java - How to load/reference a file as a File instance from the classpath - Stack Overflow
0 Eclipse dynamic web project with Java: where to store and how reference datasets? 1 How to read image as FileInputStream from source folder? 1 Spring Boot: File object must be constructed either from Resources file (classpath:) or a regular absolute path More on stackoverflow.com
🌐 stackoverflow.com
java - How to create a file from classpath - Stack Overflow
Do you want to read the file-contends ... create a new one? Please show the Line of Code where that Exception occurs. ... Save this answer. ... Show activity on this post. You are not passing the image data to the file!! You're trying to write an empty file in the path of the image!! I would recommend our Apache friends FileUtils library (getting classpath as this ... More on stackoverflow.com
🌐 stackoverflow.com
August 20, 2015
Adding files to java classpath at runtime - Stack Overflow
Is it possible to add a file (not necessarily a jar file) to java classpath at runtime. Specifically, the file already is present in the classpath, what I want is whether I can add a modified copy of More on stackoverflow.com
🌐 stackoverflow.com
java - How can I save a file to the class path - Stack Overflow
Every self-respected Java developer knows this. 2014-10-21T12:45:22.86Z+00:00 ... This answers how to update a file that exists on the classpath, but will not allow you to create a file due to getResource returning null. 2017-01-12T18:09:15.353Z+00:00 ... The counterpart of using URI, is you have to capture URISyntaxException. 2017-09-18T10:40:19.587Z+00:00 ... You can try the following provided your class is loaded from ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
How to do in Java
howtodoinjava.com › home › i/o › reading a file from classpath in java
Reading a File from Classpath in Java
April 11, 2022 - To read any file from the classpath in a class, we have to get the reference of the system classloader for that class that is trying to read the file. System classloader obviously knows the other paths for the application.
🌐
Oracle
docs.oracle.com › javase › tutorial › deployment › jar › downman.html
Adding Classes to the JAR File's Classpath (The Java™ Tutorials > Deployment > Packaging Programs in JAR Files)
The last line won't be parsed properly if it doesn't not end with a new line or carriage return. We then create a JAR file named MyJar.jar with the following command: ... Manifest-Version: 1.0 Class-Path: MyUtils.jar MyLibs/Lib.jar MyResources/ Created-By: 1.8.0_422 (Oracle Corporation) Consequently, when the Java application is launched from within the MyApp directory, the classes in MyJar.jar, in addition to being able to access the classes and resources that are part of MyJar.jar, can also access classes and resources that are contained in the MyUtils.jar and MyLibs/Lib.jar JAR files and the MyResources/ directory.
🌐
Delft Stack
delftstack.com › home › howto › java › java read file from classpath
How to Read File From Classpath in Java | Delft Stack
February 14, 2024 - Particularly beneficial in modular projects, these methods ensure efficient and concise file access, contributing to the overall simplicity and effectiveness of Java programming in version 7 and later. The code snippet below exemplifies how to use Paths and Files to read a file from the classpath.
Find elsewhere
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.

🌐
Baeldung
baeldung.com › home › spring › access a file from the classpath in a spring application
Access a File from the Classpath using Spring | Baeldung
March 26, 2025 - return new ClassPathResource("data/employees.dat", this.getClass().getClassLoader()); ... Note that from Resource, we can easily jump to Java standard representations like InputStream or File.
🌐
GeeksforGeeks
geeksforgeeks.org › java › read-a-file-from-the-classpath-in-java
How to Read a File From the Classpath in Java? - GeeksforGeeks
July 23, 2025 - // Java Program to Read a File from the Classpath import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; // Driver Class public class MyClass { // Main Function public static void main(String[] args) { // Filename String filePath = "MyFile.txt"; // Loading the current class's class loader for inputStream InputStream inputStream = MyClass.class.getClassLoader().getResourceAsStream(filePath); // Checking if the class loaded successfully if (inputStream != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReade
🌐
Oracle
docs.oracle.com › javase › › 7 › docs › technotes › tools › windows › classpath.html
Setting the class path
C:> sdkTool -classpath classpath1;classpath2... ... A command-line tool, such as java, javac, javadoc, or apt. For a listing, see JDK Tools. ... Class paths to the .jar, .zip or .class files.
🌐
Medium
medium.com › javarevisited › back-to-the-basics-of-java-part-1-classpath-47cf3f834ff
Tutorial on how Java classpath works | Javarevisited
May 15, 2022 - ClasspathProject/src/java/myprogram/ | ---> Main.java | ---> utils/ | ---> Util.java · And here are the source files just so you know what we are dealing with. ... I will be using this structure for the following parts as well so If you want to follow along I suggest you create it as well before proceeding. If you are new ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › loading-resources-from-classpath-in-java-with-example
Loading Resources from Classpath in Java with Example - GeeksforGeeks
July 23, 2025 - InputStream instr = obj.getClass().getClassLoader().getResourceAsStream(fileName); // reading the files with buffered reader InputStreamReader strrd = new InputStreamReader(instr); BufferedReader rr = new BufferedReader(strrd); String line; // outputting each line of the file. while ((line = rr.readLine()) != null) System.out.println(line); } } ... Code 2: Using getResource() method. ... // Java program to load resources from Classpath // using getResource() method.
🌐
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
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.
🌐
Baeldung
baeldung.com › home › java › java io › how to read a file in java
How to Read a File in Java | Baeldung
January 8, 2024 - The main difference is that when using the getResourceAsStream on a ClassLoader instance, the path is treated as absolute starting from the root of the classpath. When used against a Class instance, the path could be relative to the package, or an absolute path, which is hinted by the leading slash. Of course, note that in practice, open streams should always be closed, such as the InputStream in our example: InputStream inputStream = null; try { File file = new File(classLoader.getResource("fileTest.txt").getFile()); inputStream = new FileInputStream(file); //... } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
🌐
How to do in Java
howtodoinjava.com › home › java basics › java classpath
How to set CLASSPATH in Java - HowToDoInJava
February 23, 2023 - ... Apart from setting the classpath to the environment variable, you can pass an additional classpath to Java runtime while launching the application using –classpath option or –cp option.
🌐
Mkyong
mkyong.com › home › java › java – read a file from resources folder
Java - Read a file from resources folder - Mkyong.com
September 4, 2020 - In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath.
🌐
W3Docs
w3docs.com › java
How to read text file from classpath in Java?
Here's an example of how you can read a text file from the classpath in Java: InputStream is = getClass().getClassLoader().getResourceAsStream("file.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close();