简体   繁体   中英

access folder in spring boot in classpath

I am trying to get access to a folder that is created in the classpath in a Spring boot application. A snippet of the code is below:

ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
URL url = classLoader.getResource("converters");
LOGGER.debug("**************** url: " + url);
File file = new File(url.toURI());
        
Path path = Paths.get(file.getAbsolutePath());
Arrays.stream(path.toFile().listFiles()).forEach(f -> LOGGER.debug("*******files: " + f.getName()));
if (!path.toFile().isDirectory()) {
   throw new IllegalArgumentException(ErrorCode.INVALID_MAPPERS_DIRECTORY.formatMessage(path));
}

The code above runs without any issues when I run it in Intellij and I get the url as below:

file:/C:/Users/user1/projects/my-service/test/build/resources/main/converters

When I run it on Linux inside the application rpm, I get the url value below:

jar:file:/opt/home/libexec/my-service-2.0.0-SNAPSHOT.jar./BOOT-INF/lib/my-service-api-2.0.0-SNAPSHOT.jar!/converters

Any reason why is the different behavior?

The difference is the packaging. Your IDE does not package your application to run it, it just uses the file system as this is faster. When you package your app and deploy all the resources that your ide can access from the file system are now packaged within your spring boot fat jar file. In your case the file is inside the my-service-api-2.0.0-SNAPSHOT.jar which is packaged inside your fat jar.

Problem

I need to be able to have a reference to a folder that a user may create in the classpath of my Spring Boot application.

Solution

The following worked for me:

mapperFilesFolder = resolver.getResources("classpath*:" + mappersLocation + "/.");
Path path = Paths.get(mappersFolder[0].getURI());

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