9

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.

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

2 Comments

If you put the test.txt into the com/example package it will not work. To get that working correctly you need to put the test.txt into src/main/resources nothing else.
Okay. I think I understand now. So getResource interprets paths relative to the class instance (so since Main is in com.example I was accidentally looking for src/main/resources/com/example/test.txt instead of src/main/resources/test.txt)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.