Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

maven

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.

like image 605
user1930555 Avatar asked Dec 26 '12 19:12

user1930555


1 Answers

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
like image 183
Werner Kvalem Vesterås Avatar answered Nov 06 '22 21:11

Werner Kvalem Vesterås