I am using Spring with Maven and I would like to load a file contained in the maven folder src/main/resources
inside a spring service annotated with @Service
contained in a JAR
file (used by another WAR
file as a Maven dependency). This does not seem to work for many different reasons (read: for many different exceptions according to many different attempts).
- I know that Maven, when building, puts the stuff in
src/main/resources
at the root of theJAR
file. I've opened theJAR
file and I've verified that. - I would prefer a
File
object (something I can use with utility libraries like Apache Commons IO), but also "something" else that's working is fine. - I would prefere going for stuff within the Java class annotated with
@Service
(i.e. no application context XML file, with stuff inside that I recall within the service etc.) - The file contains stuff that I eventually use as a
List<String>
where every item is a line in the original file. I need to keep this file as it is, I can not use a database or another solution different than a file. - This is not a
.properties
file and is not intended to be.
The following are the not working attempts (throwing NullPointerException
, FileNotFoundException
, IllegalArgumentException: URI is not hierarchical
and so on...).
Among the attempts I have tried also adding/removing the prefix src/main/resources
while trying to figure out what was wrong, but then I figured out that Maven puts all the stuff at the root of the JAR
file as stated before.
@Value("classpath:src/main/resources/myFile.txt")
private Resource myFileResource;
private File myFile =
new File(this.getClass().getResource("/myFile.txt").toURI());
private File myFile =
new FileSystemResource("src/main/resources/myFile.txt").getFile();
private BufferedReader bufferedReaderMyFile =
new BufferedReader(
new InputStreamReader(getClass().getResourceAsStream("myFile.txt")));
What's wrong with what I am doing?