I have a Spring Boot application with a java resource folder:
src
|
main
|
resources
|
test
|
test1.json
test2.json
...
In the resource folder there are json files. I can read these files within my IDE (IntelliJ). But as a compiled JAR file, I get Nullpointer exceptions.
Spring Boot copies the files to: BOOT-INF/classes/test Is it possible to read the resource files within a JAR file? I don't know the file names. So in first, I have to get all file names and the read each file.
Does anyone have an idea?
UPDATE
I have tried this:
Resources[] resources = applicationContext.getResources("classpath*:**/test/*.json");
With that I'm getting all file paths. But that needs too much time. And even if I get the file names, how would I read the files?
This actually works using a ResourcePatternResolver
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath*:test/*.json");
for(Resource r: resources) {
InputStream inputStream = r.getInputStream();
File somethingFile = File.createTempFile(r.getFilename(), ".cxl");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}
LicenseManager.setLicenseFile(somethingFile.getAbsolutePath());
log.info("File Path is " + somethingFile.getAbsolutePath());
}
The below solution will read the files into a Map.
Here you read your resources:
Resource[] resources = applicationContext.getResources("classpath*:test/*.json");
for (Resource r: resources) {
processResource(r);
}
Here you process your resources:
// you need to add a dependency (if you don't have it already) for com.fasterxml.jackson.core:jackson-databind
ObjectMapper mapper = new ObjectMapper();
private void processResource(Resource resource) {
try {
Map<String, Object> jsonMap = mapper.readValue(resource.getInputStream(), Map.class);
// do stuffs with your jsoMap
} catch(Exception e){
e.printStackTrace();
}
}
}