0

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?

1
  • 1
    You can't assume that the classpath contains folders or Files, period. You have to use another strategy; which depends on the specific task at hand. Commented Dec 1, 2020 at 2:47

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Hopey One, for the answer, it makes sense but is there a way I can have reference to a folder or directory in the classpath on the file system?
0

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()); 

2 Comments

Why exactly is there a need to involve the classpath into this logic? It seems to me that when you have a directory on the filesystem where a user can do things and stuff with a file and the application can read from it... you're done.
@Gimby, we need to be able to watch any changes the user makes to the files and if such changes occur we need to validate and reload without starting the application. A user can specify any location for the files but the default is a folder that exists in the class path if it is not specified.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.