Eivyses
Eivyses

Reputation: 361

Spring boot: trying to read directory content inside resources folder produces FileNotFoundException when reading from jar

so I have a problem with Spring-boot. Basically the idea is that in resources i have a directory called migrations which stores sql scripts that needs to be launched. It works well on local machine. But, as soon as I upload project to server i get greeted with error of:

Caused by: java.io.FileNotFoundException: class path resource [migrations] cannot be resolved to absolute file path because it does not reside in the file system: 

A lot of googling helped me to identify problem. It has to do with file being in .jar, when I do read directory as InputStream, as stated in other issues like this one, I can get specific file and access it's scripts if I specify full name of that resource, like resourceLoader.getResource("classpath:migrations/file.sql")
But, specifying full name of resource like that and defining all the file names is not an option, since in the future this folder can expand a lot and i don't want to manually edit code to add file to running.
Is there any workaround for this issue that would allow me to at least read file names from directory and then access them one by one?

Upvotes: 1

Views: 1370

Answers (1)

DarkVision
DarkVision

Reputation: 1423

i don't think there is a good solution for that if it deploy has a jar unless you use docker file to copy the resource and deploy it. getInputStream() was always the best solution to get file from anywhere.

maybe this solution but not try yet

ClassLoader cl = this.getClass().getClassLoader(); 
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
Resource[] resources = resolver.getResources("classpath*:/*.sql") ;
for (Resource resource: resources){
    do your things maybe print the name resource
}

Upvotes: 4

Related Questions