How can I read a file from the classpath?

  • 0
    Greetings to the reader!
    I need help getting the file from the classpath.
    The file is specified in the -cp option when running jar through the console.

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

    At the output I get:
    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?
    Java Fynn Blackwell, Jun 19, 2020

  • 1 Answers
  • 0
    It was like that,

    That the classpath only works with .jar and directories, so specifying a file in the -cp argument is wrong.


    java -cp myjar.jar :.

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!