Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ClassLoader.getSystemResource to get file path in JAVA

Tags:

java

tomcat

I'm writing a dynamic web module using Tomcat 7 with Eclipse and Java 8, and my problem is that a required JAVA project on the build path is using the following to load files (lexicons, dictionaries, etc):

String filePath = "conf/test.txt"; // my test file is in WEB-INF/conf
String absolutePath = ClassLoader.getSystemResource(filePath).getPath();

I'm getting a null pointer so it's not finding the file.

When using the following, it finds the file:

String absolutePath = new File(filePath).getAbsolutePath();

The problem is:

I am required to use ClassLoader.getSystemResource. How can I specify my file's path for it to work without getting a null pointer (without using absolute paths too)?

like image 205
P-S Avatar asked Sep 18 '26 08:09

P-S


1 Answers

Problem you have is that SystemClassLoader used to start the program, so given you are trying to search for a resource in a web container such as tomcat, this will NOT work.

If I were you, I would just use the following,

this.getClass().getResource(“/top.txt”)
like image 154
Ducaz035 Avatar answered Sep 20 '26 22:09

Ducaz035



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!