pandagrammer
pandagrammer

Reputation: 871

Java class.getResource() returns null

I am trying to use files in resource directory that was marked as "resource root" in IntelliJ, but the below code fails to find the file.

Could you tell me what was wrong? thanks.

Project hierarchy

public class ResourceTest {
    public void testResource() {
        URL url = this.getClass().getResource("resources/table.1gram");
    System.out.println(url);
}
public static void main(String[] args) {
    ResourceTest rt = new ResourceTest();
    rt.testResource();
}

}

Upvotes: 0

Views: 7008

Answers (1)

Andreas
Andreas

Reputation: 159086

Files in the resources folder will be packaged to the root of the .jar file, meaning that during development, the resources folder itself is in the classpath, so you need this.getClass().getResource("/table.1gram"), or without the / since your class is in the unnamed package, aka also in the root of the .jar file.

Upvotes: 7

Related Questions