javaspring-bootmavenclasspathjava-resources

Where do I put my resource file to make it readable in Spring using classpath?


I'm trying to load a text file with Java, Maven & Spring, following the examples at

https://www.baeldung.com/spring-classpath-file-access#3-using-resourceloader

Also using this guide as the base for my application and structure

https://spring.io/guides/gs/spring-boot/

The Baeldung guide uses code like this to create a Resource

resourceLoader.getResource(
  "classpath:data.txt");

And when I run this code, I get an IOException

class path resource [data.txt] cannot be opened because it does not exist

What the guide doesn't say is where I need to put this file to make it available.

I suppose classpath is a path relative to the class, in this case "HelloController.java"

In my project file structure, this class is located at src/main/java/com/example/demo/HelloController.java

so I put the text file at src/main/resources/com/example/demo/data.txt which is not working. Where does the file need to be to make it readable?


Solution

  • Helped by this post Spring Boot classpath I tried to put the file directly in the "resources" folder, and then it worked.

    src/main/resources/data.txt