Java 11 and Spring Boot here. I have the following project directory structure:
myapp/
application.yml
app/
src/
main/
java/
resources/
test/
java/
resources/
smoke/
file1.txt
I have some code:
File resourceFile = org.springframework.util.ResourceUtils.getFile("smoke/file1.txt");
String filePath = resourceFile.getAbsolutePath();
At runtime, filePath has a value of:
/Users/myuser/workspace/myapp/app/checksum-tests/test-file.txt
When it should be:
/Users/myuser/workspace/myapp/app/src/test/resources/checksum-tests/test-file.txt
Why is this? And more importantly, how can I use ResourceUtils or something similar in Spring-land to fetch a valid (exists on the file system) File to a test resource?
As mentioned in the Spring Documentation for ResourceUtils
In the JavaDoc of ResourceUtils it says
So using ResourceUtils is not recommended. There are many ways to getting the files. You can use Spring's ResourceLoader if you want spring implementation
And in the method you can use
Or you can use ClassLoader
If you use Spring Boot then this should give a path with in the target folder.This is because the ClassLoader looks for the resources on the classpath. In Maven, the compiled classes and resources are put in the /target/ directory. That's why this time, we get a path to a classpath resource.
E.g.
D:\file-tester\target\classes\smoke\test-file.txt