user1930555
user1930555

Reputation: 93

How can I add src/main/resources to the classpath when using mvn exec:java

I'm trying to run the following application which attempts to load a file (src/main/resources/test.txt) from the classpath:

package com.example;

public class Main {
    public static void main(String[] args) {
        System.out.println(Main.class.getResource("test.txt"));
    }
}

When I do mvn exec:java -Dexec.mainClass=com.example.Main, I get null printed out on the command line.

So how do I get the files in src/main/resources added to the classpath? Note that I ran mvn package, checked the generated target/test.jar, and confirmed that it included test.txt at the top level.

Upvotes: 9

Views: 7513

Answers (1)

A slash should solve it

System.out.println(Main.class.getResource("/test.txt"));

Your code would work if you placed the test.txt file under:

src/main/resources/com/example

Upvotes: 7

Related Questions