java - 如何在 Spring Boot MVC 中加载文件?
问题描述
我发现的所有示例都使用 XML 配置文件。我尝试了以下方法:
IdSClientConfigurationImpl config = new IdSClientConfigurationImpl("idsclient.properties");
config.load();
它给了一个例外
java.io.FileNotFoundException: idsclient.properties (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method) ~[na:1.8.0_152]
at java.io.FileInputStream.open(FileInputStream.java:195) ~[na:1.8.0_152]
at java.io.FileInputStream.<init>(FileInputStream.java:138) ~[na:1.8.0_152]
at com.cisco.ccbu.common.ids.client.impl.IdSClientConfigurationImpl.load(IdSClientConfigurationImpl.java:82) ~[idsclientlib-11.6.1.jar:na]
我将文件放在与application.properties
.
$ find src -name idsclient\*
src/main/resources/idsclient.properties
它被复制到类文件夹期间mvn spring-boot:run
$ find target -name idsclient\*
target/classes/idsclient.properties
那么在 Spring Boot 应用程序的上下文中文件的真实路径是什么?
我也试过
IdSClientConfigurationImpl config = new IdSClientConfigurationImpl("classpath:/idsclient.properties");
但它给了
java.io.FileNotFoundException: classpath:\idsclient.properties(文件名、目录名或卷标语法不正确)
解决方案
您可以使用Spring 资源(ClassPathResource)
//either autowire
@Value("classpath:idsclient.properties")
private Resource idsclientResource;
//or construct manually
ClassPathResource idsclientResource = new ClassPathResource("idsclient.properties");
...
IdSClientConfigurationImpl config = new IdSClientConfigurationImpl(idsclientResource.getFile().getPath());
推荐阅读
- git - 如何将 Unity3D 项目中的 SteamVR 资产添加到版本控制?
- java - 如何在没有模块的情况下升级到 Java 11?
- java - 如果 array 或 arrayList 引用前一个元素,我如何实现一个函数以返回 true?
- javascript - 如何防止客户端刷新页面?
- reactjs - React 组件可以渲染存储在其状态中的另一个组件吗?
- exact-online - 为 Exact Online 从 PHP 客户端库更新记录
- angular - Angular 7 - 访问服务返回未定义的 observable
- unity3d - Unity3d - 碰撞功能跳跃
- haskell - 如何优化并行排序以提高时间性能?
- c - 将 char [] 附加到 char* content = realloc(NULL, sizeof(char) * 10);