0

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();
}

}

pandagrammer
  • 841
  • 2
  • 12
  • 24
  • 6
    "resources" vs. "resources2", "table.1gram" vs "table1.1gram". – Marvin Dec 03 '15 at 21:14
  • @Marvin sorry there were typos, but it still doesn't work after fixing those typos. – pandagrammer Dec 03 '15 at 21:17
  • try to change "resources/table.1gram" for "classpath:resources/table.1gram" – Rafał P Dec 03 '15 at 21:22
  • @RafałPieńkowski did you mean to replace "classpath" with actual class path? When I literally used "classpath:resources/table.1gram", it still returned null. :( – pandagrammer Dec 03 '15 at 21:24
  • I suspect the path of the resource file. I'm not familiar with IntelliJ, but could you find out how the resource file and class file are placed in the target folder or OUT in your case may be? – Aragorn Dec 03 '15 at 21:29
  • Hmm I'm not sure about IntelliJ's folder structure, but try to put your resource folder under src folder. And then try both approaches: with and without classpath – Rafał P Dec 03 '15 at 21:29
  • You could even try "/resources/table.1gram" to tell class loader to look from the root of jar – Aragorn Dec 03 '15 at 21:29

1 Answers1

7

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.

Andreas
  • 154,647
  • 11
  • 152
  • 247