Charles W
Charles W

Reputation: 2292

How do I get the path of a resource when using Maven?

This is what I've tried:

String myPath = myStaticClass.class.getResource("en-us").getPath(); 
// returns C:/Users/Charles/Workspace/ProjectName/target/classes/

My resources are in C:/Users/Charles/Workspace/ProjectName/src/main/resources

Does anyone know why this is happening?

Edit:
I suppose I should have mentioned that the path is being used in a library to load resources, but is failing.

Upvotes: 2

Views: 206

Answers (3)

Alexandre Santos
Alexandre Santos

Reputation: 8338

You are asking why this is happening and you are saying you want to load the resources.

The "why": see the other posts. No reason to duplicate them here.

The "how": the following code shows how to load the resources. Assuming they are in a file called "your.resources" and that this file is in the classpath; which, according to your post, it is.

import java.io.IOException;
import java.util.Properties;

public class Test {

    public Test() throws IOException
    {
        final Properties properties = new Properties();
        properties.load(this.getClass().getResourceAsStream("your.resources"));
        System.out.println(properties);
    }
    public static void main(String[] args) throws IOException  {
        new Test();
    }
}

Note that you don't need to provide the full path of the resources. As long as they are in the classpath, this will find them.

Upvotes: 0

Daniel Kaplan
Daniel Kaplan

Reputation: 67300

When you run mvn compile, one of the steps along the way is to copy your resources directory to the target/classes directory. Now usually if you call myStaticClass.class.getResource, the path you pass in will have target/classes as the root. So lets say you have a file at src/main/resources/my.file.txt You will be able to get it by calling myStaticClass.class.getResource("/my.file.txt");

The thing you're probably forgetting is the "/" there. Without that "/", it will look relative to your class' directory.

Alternatively, you could do this: ClassLoader.getSystemClassLoader().getResource("my.file.txt").getPath(). Notice the lack of a slash.

Upvotes: 2

Jason
Jason

Reputation: 11832

That is where your compiled code is put when you use maven to build your project. Your resources are being copied to the target/classes folder as part of the build process.

If you then deploy your application to another location, you will find that your code will return the new path to the resource.

Edit

As per your comment, try using the following to load your resource:

InputStream resourceStream = myStaticClass.class.getClassLoader().getResourceAsStream("en-us");

This uses the current class's class loader to locate and provide an InputStream to your resource.

Upvotes: 3

Related Questions