My Spring Boot application has the standard structure of src: main, test
each of which has a /resources
subfolder.
I need to reference an existing file under /resources
. When I do
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("file.txt");
everything works great. But when I construct a File as follows, including with classpath:
, the file is invalid and file.isValid()
returns false.
File f1 = new File("file.txt");
File f2 = new File("classpath:file.txt");
File f3 = new File("resources/file.txt");
File f4 = new File("classpath:resources/file.txt");
File f5 = new File("/resources/file.txt");
File f6 = new File("classpath:/resources/file.txt");
File f7 = new File("classpath:/file.txt");
I can't use anything involving getClass().getClassLoader().getResource()
and must use a dynamic file path because I'm dealing with a property which works (1) either from a classpath reference in the source code or (2) as a real file, overridden on the server. So I have to get File objects in a uniform way -- it's a single property referencing this file. Are there any solutions?
e.g.
file_location = classpath:file.txt # for local testing
file_location = /opt/dir/file.txt # server override
This thread says that ClassLoader/Resource methods must be used with File
.