How do I use the file from classpath?

I need help getting a file from a file to use it. The file is specified in the -cp option when running jar through the console.

run the jar using:

java -cp myjar.jar:dir1/dir2/myfile.txt

execution result:

Exception in thread "main" java.lang.NullPointerException

source code:



public class Main {

    public static void main(String[] args) {
        ClassLoader classLoader = Main.class.getClassLoader();
        InputStream resource = classLoader.getResourceAsStream("dir1/dir2/myfile.txt");         

project tree

-- сom
---- company

How do I get that file from -cp?


Since you specify dir1/dir2/myfile.txt in the getResourceAsStream() call, you want the directory containing dir1 on the classpath, which would be the working directory, i.e. .:

java -cp myjar.jar:.

The classpath can only specify:

  • Directories
  • Jar files

No other type of file is supported.

Source: stackoverflow