0

My project directory structure (in Eclipse):

MyProject/
    src/main/Java
    src/main/resources  
        stories
            file.story

In Main class i have return below line which return null while excuting main class through MAVEN

String folderName = "stories";
URL appURL = ClassLoader.getSystemClassLoader().getResource(folderName);

While executing through maven, appURL returns NULL.

By reading one post on Stackoverflow i got to kanow that, i am running the webapp on server but there is no reference to the resources on the server so we need to add some code in POM.xml file. i have added below code in POM.xml file but still its not working :(

<resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>stories</include>
            </includes>
        </resource>

    </resources>

Looking for help.

DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
Hema
  • 13
  • 1
  • 8
  • Can you try with this alternative getClass().getClassLoader().getResource(...) as an alternative to ClassLoader.getSystemClassLoader().getResource(...) – Pradeep Apr 03 '17 at 06:54
  • Getting error as "cannot make static reference to non-static method" because above code is in main method. – Hema Apr 03 '17 at 08:37
  • Hi you need to create object of your class like YourClass a= new YourClass(); and then you need to call a.getClass().getClassLoader().getResource(...) – Pradeep Apr 03 '17 at 10:03

1 Answers1

1

There are two ways you can achieve this

Approach 1)

If it is not inside the main method URL url = getClass().getClassLoader().getResource("someresource.xxx"); If it is inside main you need to create object of your class and then call getClass on it .

Approach 2)

By extending URLStreamHandler

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class YourClass extends URLStreamHandler {
    /** The classloader to find resources from. */
    private final ClassLoader classLoader;

    public YourClass() {
        this.classLoader = getClass().getClassLoader();
    }

    public YourClass(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        final URL resourceUrl = classLoader.getResource(u.getPath());
        return resourceUrl.openConnection();
    }
}

Ref:URL to load resources from the classpath in Java

Community
  • 1
  • 1
Pradeep
  • 1,947
  • 3
  • 22
  • 45
  • Thank you so much for your help, Pradeep. It worked. I have created object of class then used getclass() method – Hema Apr 03 '17 at 11:45