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 com.company.Main

execution result:

Exception in thread "main" java.lang.NullPointerException
  at com.company.Main.main(Main.java:11)

source code:

package com.company;

import java.io.InputStream;

public class Main {

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

project tree

-- сom
---- company
------ Main.java

How do I get that file from -cp?

Answer

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:. com.company.Main

The classpath can only specify:

  • Directories
  • Jar files

No other type of file is supported.



Source: stackoverflow