我正在尝试列出位于 SpringBoot 应用程序的/src/main/resource/文件夹中的文件夹的内容。该文件夹包含常规文件。该代码在 IDE (STS) 中运行得非常好,但在应用程序打包后就不行了。
这是代码:
Resource xCatRawResource = resourceLoader.getResource(xCatRawResourcePath);
try(
InputStream in = xCatRawResource.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in))
)
{
byte[] bdata = FileCopyUtils.copyToByteArray(in);
String data = new String(bdata, StandardCharsets.UTF_8);
// data is an empty String when app is packaged
}
catch(IOException ioe) {
LOGGER.error("Unable to parse XCAT names", ioe);
}
我尝试了不同的策略(使用 ResourceUtils 等...)但没有成功。
非常感谢您的帮助!
最佳答案
尝试使用 Reflections 库 - 了解更多相关信息 here .:
最新版本的 POM:
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.12</version>
</dependency>
如何使用它的示例:
假设您的 /src/main/resource/
目录中有一个名为 jsonfiles
的目录。
以下代码将打印出jsonfiles
目录的内容:
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.ClasspathHelper;
import java.util.regex.Pattern;
import java.util.Set;
...
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("YOUR.PACKAGE.NAME.HERE"))
.setScanners(new ResourcesScanner()));
Set<String> resources = reflections.getResources(Pattern.compile("jsonfiles.*"));
resources.forEach((resource) -> {
System.out.println(resource);
});
输出将是这样的:
jsonfiles/json_file_one.json
jsonfiles/json_file_two.json
我已经在 fat/uber JAR 中对此进行了测试。
免责声明:我不使用 Spring - 所以如果这以某种方式导致您的问题,那么我的解决方案可能不起作用。但我希望它能够。
(一点:我注意到,在您的问题中,您的代码定义了一个您不使用的缓冲读取器br
- 您使用输入流in
。)
关于java - 在 Spring Boot 中浏览 uber jar 中嵌入的文件夹的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60677370/