繁体   English   中英

在类路径中启动 spring 中的访问文件夹

[英]access folder in spring boot in classpath

我正在尝试访问在 Spring 启动应用程序的类路径中创建的文件夹。 代码片段如下:

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

上面的代码在 Intellij 中运行时没有任何问题,我得到 url 如下:

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

当我在应用程序 rpm 内的 Linux 上运行它时,我得到以下 url 值:

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

为什么会有不同的行为?

区别在于包装。 您的 IDE 不会 package 您的应用程序来运行它,它只是使用文件系统,因为这样更快。 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. 在您的情况下,该文件位于my-service-api-2.0.0-SNAPSHOT.jar中,该文件封装在您的胖 jar 中。

问题

我需要能够引用用户可能在我的 Spring 引导应用程序的类路径中创建的文件夹。

解决方案

以下对我有用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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