-1

Seems like whatever I do I cannot read a file from resources dir in my Spring-boot app.

Any ideas?

Could it be because of the way I call the method to read the file?

@SpringBootApplication
public class DemostoreApplication {

public static void main(String[] args) throws IOException {

    SpringApplication.run(DemostoreApplication.class, args);
}

@EventListener(classes = ApplicationStartedEvent.class)
public void applicationStarted() {
    loadAFile();
}

void loadAFile(){
    InputStream inputStream = getClass().getResourceAsStream("user-data.txt");
   }
}

I can see that there are many questions like this one, mostly unanswered. I've tried the propositions in all of them.

gai-jin
  • 653
  • 2
  • 10
  • 24
  • I doubt you tried all of them. Use the spring resource loading mechanism. Use a `ClassPathResource` to load this. – M. Deinum Sep 30 '20 at 12:35
  • I am more curious WHY the approach in the sample code is not working. – gai-jin Sep 30 '20 at 12:37
  • 1
    Because it loads files from the location of the class, so the file should be next to the class. So either you need to prefix with a `/` indicating from the root or use the classloader (instead of the class) to load the resource. When using the Spring `ClassPathResource` it always starts from the root preventing you from this mistake. – M. Deinum Sep 30 '20 at 12:51
  • 1
    https://stackoverflow.com/questions/44399422/read-file-from-resources-folder-in-spring-boot duplicate – Rajarshi Das Sep 30 '20 at 12:53

1 Answers1

0

Yes, I go the answer.

A / should be added, denoting relative to the root of the project!

Otherwise the file is looked for in the directory relative to the class's package. Stupid me.

This is working:

InputStream is = getClass().getResourceAsStream("/user-data.txt");
gai-jin
  • 653
  • 2
  • 10
  • 24