我正在开发一个springboot应用程序。我需要加载一个在参考资料中的文件。如果我运行单元测试(maven,以防万一),那么可以毫无问题地加载该文件。。。甚至是集成测试。但当我运行应用程序时,
真的吗
,然后就找不到了。我尝试了几种不同的方法来实现它,但都失败了:
java.lang.IllegalArgumentException: resource path-to-file not found.
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:217) ~[grpc-1.23.jar!/:?]
at com.google.common.io.Resources.getResource(Resources.java:195) ~[grpc-1.23.jar!/:?]
java.io.FileNotFoundException: class path resource [path-to-file] cannot be resolved to absolute file path because it does not exist
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:177) ~[spring-core-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
文件在中
WEB-INFO/classes/path-to-file
从哪来的
src/main/resources/path-to-file
在我的项目中。
更新1
从罐子
,代码非常简单:
ClassPathResource cl = new ClassPathResource(resourcePath);
URL url = cl.getURL();
String content;
try (InputStream in = url.openStream()) {
content = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
LOG.info("Content from {} is {} bytes long", resourcePath, content.length());
return content;
提示来自标记为已接受的答案。谢谢!