nimo23
nimo23

Reputation: 5700

class.getResource() within Java-EE (wildfly)

I am using Java-EE (Wildfly v.17)

I want to access the file "config.txt" which resides within WEB-INF/classes/config.txt.

I know one solution with servletContext.

However, I am wondering why something common does NOT work:

// prints: file:/Users/test/server/wildfly-17.0.1.Final/modules/system/layers/base/org/jboss/as/ejb3/main/timers/
// why does this point to "ejb3/main/timers" ???
log.info(User.class.getResource("/").toExternalForm());

Nothing of those works, I always get java.lang.NullPointerException (no file found, but the file is there!)

var resource = User.class.getResource("/config.txt");


var resource = User.class.getResource("/WEB-INF/classes/config.txt")


var resource = User.class.getResource("config.txt")


var resource = getClass().getResource("config.txt")


var resource = Thread.currentThread().getContextClassLoader().getResource("config.txt")

How can I use getResource() or getResourceAsStream() within Wildfly?

(Or where should I put the config.txt to be able to use getResource() ?)

Upvotes: 2

Views: 1823

Answers (2)

m.hassaballah
m.hassaballah

Reputation: 250

Jboss AS7 or wildfly use its internal module structure during class loading mechanism , so when you call getResource method to load the file (external file), it tries to load the file using ejb3 module ( ) and the ejb3 module try to load the file from timers folder

<module xmlns="urn:jboss:module:1.5" name="org.jboss.as.ejb3">
    <properties>
        <property name="jboss.api" value="private"/>
    </properties>

    <resources>
        <artifact name="${org.wildfly:wildfly-ejb3}"/>
        **<resource-root path="timers" />**
    </resources>

You can try the below suggestions :-

  • move your configuration file under timers folder

  • create your module and force jboss to load the classes from your module, you can find the steps inside the following link "https://developer.jboss.org/wiki/HowToPutAnExternalFileInTheClasspath"

  • move your configuration file under resource folder "src/main/resources" and load it as resource stream

Upvotes: 1

Steve C
Steve C

Reputation: 19445

The easiest way to get access to the data in your WEB-INF/classes/config.txt file is to use java.lang.Class.getResourceAsStream("/config.txt"), which is covered by your first example.

If this returns null then the file is not present. If you're building with Maven then the most common reason for this is placing config.txt in the src/main/java directory instead of src/main/resources.

Attempts to use java.lang.Class.getResource("/config.txt") will end in disappointment because the URL that is returned will likely contain a scheme that is tricky or impossible to use, such as "jar://..." or "vfs://...". You cannot rely upon WildFly to return a "file://.." style of URL for a class-loader resource.

Upvotes: 6

Related Questions