简体   繁体   中英

Read directory from Spring Boot's Fat JAR

I'm trying to read the resources/configs directory in my Spring Boot 2 application. Here is the example of the structure of the directory:

resources
| configs
| | file1.xml
| | file2.xml
| | ...

Code where I'm reading the directory and the nested files:

@Value("${app.configs-path}")
String configsPath;

...

Resource configsDirectoryResource = new ClassPathResource(configsPath);
InputStream configsDirectoryStream = configsDirectoryResource.getInputStream();
InputStreamReader configsDirectoryStreamReader = new InputStreamReader(configsDirectoryStream);
BufferedReader configsDirectoryBufferedReader = new BufferedReader(configsDirectoryStreamReader);

List<String> configFileNames = configsDirectoryBufferedReader.lines().collect(toList());

And my application.properties :

app.configs-path=configs

When I run my application in IDE, this works fine. The object configsDirectoryResource returns stream of filenames, and then I read every nested file. But when I launch the JAR file, configsDirectoryResource returns no filenames. However I can read XML files directly, but I'd like to get list of files in runtime.

How can I read the directory or get list of files in the directory which is in the JAR file?

You can use PathMatchingResourcePatternResolver from Spring Framework.

Example code:

ClassLoader cl = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
Resource[] resources = resolver.getResources("classpath*:/"+configsPath+"/*.xml") ;
for (Resource resource: resources){
    logger.info(resource.getFilename());
}

OK, that was easier than I thought.

ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resourcePatternResolver.getResources(configsPath + "/*.xml");

Then we can get an InputStream from each resource and work with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM