3

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)?

2
  • Why do you specifically need to use #getsystemResource() ? Commented Apr 8, 2016 at 16:34
  • Because I am using several projects written by other developers on my build paths and they all load files that way. Commented Apr 8, 2016 at 17:13

2 Answers 2

5

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”)
Sign up to request clarification or add additional context in comments.

1 Comment

If you are using getClass from a static method, you will get an error, then just use TheClassName.class instead of getClass(). Thanks to @Ducaz035
-2

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.

1 Comment

The question is how to specifically use ClassLoader.getSystemResource to find my file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.