Jai
Jai

Reputation: 352

getResource() return null in Eclipse not in JAR file

Am developing application in spring boot.I have the two packages inside src/main/java 1. com.project.test and 2. wsdl. Inside first package I have spring boot main class. inside second package I have test.wsdl file. I try to load the test.wsdl file in main class using below code

URL wsdl = MainClass.class.getClassLoader().getResource(/wsdl/test.wsdl); system.out.println("wsdl: "+wsdl);

It return null while run in Eclipse. When build application as jar and run application using java -jar app.jar. It return correct path. Why it return null in Eclipse. But when I run below code without prefix '/' like below. Its working fine in both Eclipse and JAR

URL wsdl = MainClass.class.getClassLoader().getResource(wsdl/test.wsdl); system.out.println("wsdl: "+wsdl);

But my requirement is to load resource using path /wsdl/test.wsdl

Upvotes: 0

Views: 846

Answers (2)

M. Prokhorov
M. Prokhorov

Reputation: 3993

To quote relevant Java documentation (emphasis mine):

Resource Names

A common convention for the name of a resource used by a class is to use the fully qualified name of the package of the class, but convert all periods (.) to slashes (/), and add a resource name of the form name.extension. To support this, and to simplify handling the details of system classes (for which getClassLoader returns null), the class Class provides two convenience methods that call the appropriate methods in ClassLoader.

The resource name given to a Class method may have an initial starting "/" that identifies it as an "absolute" name. Resource names that do not start with a "/" are "relative".

Absolute names are stripped of their starting "/" and are passed, without any further modification, to the appropriate ClassLoader method to locate the resource. Relative names are modified according to the convention described previously and then are passed to a ClassLoader method.

Link: Accessing Resources

Upvotes: 1

Valijon
Valijon

Reputation: 13103

You need to move wsdl/test.wsdl inside src/main/resources in order to load resource.

When you package you app.jar, wsdl/test.wsdl goes into root path inside jar file, so .getClassLoader().getResource("wsdl/test.wsdl") works as expected.

Upvotes: 1

Related Questions