How can I read a file from the classpath?
-
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 com.company.Main
At the output I get:
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?Java Fynn Blackwell, Jun 19, 2020 -
It was like that,
That the classpath only works with .jar and directories, so specifying a file in the -cp argument is wrong.
Solution
java -cp myjar.jar :. com.company.Main
Anonymous
1 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!