我正在实现一段代码,在一些配置文件中进行更改。 一开始我试图找到我的 application.properties 文件:
File file = new File(Objects.requireNonNull(this.getClass().getClassLoader().getResource("application.properties")).getFile());
文件位于 /opt/pcc/lib/smp-asnef.jar
中的 src/main/resources/application.properties
但我收到一个错误:
<块引用>错误:无法从 URL 加载配置 文件:/root/file:/opt/pcc/lib/smp-asnef.jar!/BOOT-INF/classes!/application.properties
您能解释一下这个错误吗(我想了解他究竟在何处查找文件以及它究竟意味着什么)? 什么是解决方案?
如果需要,我准备提供更多信息。
答案 0 :(得分:1)
构建路径中的资源自动在运行的Java程序的类路径中。考虑到这一点,您应该始终使用类加载器加载此类资源。看看这个:
String propName = "application.properties";
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try(InputStream resourceStream = loader.getResourceAsStream(propName)) {
props.load(resourceStream);
}
// use props here ...
或者,您可以使用此 getResourceAsStream() 方法:
import org.apache.commons.io.IOUtils;
String fileName = "application.properties";
ClassLoader classLoader = getClass().getClassLoader();
try (InputStream inputStream = classLoader.getResourceAsStream(fileName)) {
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
让我知道这是否有帮助:)
答案 1 :(得分:0)
要从 Java jar 文件中读取文件,请使用 getClass
和 getResourceAsStream
方法。
示例:
InputStream is = getClass().getClassLoader().getResourceAsStream("some_file");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// some logic
br.close();
isr.close();
is.close();
<块引用>
在某些配置文件中进行更改。
您不能更改当前使用的 jar 的任何内容。文件被视为“锁定”。 所以如果你想修改配置我建议
spring.config.location
cli 参数通知 spring