P
P
ProtCN2020-11-02 04:22:55
Java
ProtCN, 2020-11-02 04:22:55

How to read file from classpath?

A big hello to the reader!
I need help getting file from classpath.
The file is specified in the -cp option when running the jar via the console.

I run the jar using:

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


At the output I get:
Exception in thread "main" java.lang.NullPointerException
  at com.company.Main.main(Main.java:11)


Source
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 the question

In order to leave comments, you need to log in

1 answer(s)
P
ProtCN, 2020-11-02
@ProtCN

The point was that
the classpath only works with .jars and directories, so specifying a file in the -cp argument is wrong.
Decision
java -cp myjar.jar:. com.company.Main

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question