Reputation: 4016
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)?
Upvotes: 3
Views: 14551
Reputation: 3132
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”)
Upvotes: 5
Reputation: 126
Use below please...
String tempPath = new File("").getAbsolutePath();
String filePath=tempPath+"conf/test.txt";
use ClassLoader.getResource() and below is explanation...
ClassLoader::getSystemResource() uses the system classloader. This uses the classpath that was used to start the program. If you are in a web container such as tomcat, this will NOT pick up resources from your WAR file.
Class<T>.getResource() prepends the package name of the class to the resource name, and then delegates to its classloader. If your resources are stored in a package hierarchy that mirrors your classes, use this method.
ClassLoader.getResource() delegates to its parent classloader. This will eventually search for the resource all the way upto the system classloader.
Upvotes: -2