Java 无法加载application.properties文件

Java 无法加载application.properties文件,java,Java,要加载此.properties文件,我应该在此处放置什么路径?我似乎无法将其加载 InputStream stream = ProductVersionService.class.getResourceAsStream("/application.p‌​roperties"); properties.load(stream); 您需要指定属性文件的完整路径,从根目录到文件本身:/main/resources/application.properties由于您的属性文件将从war包中读取,因此最

要加载此
.properties
文件,我应该在此处放置什么路径?我似乎无法将其加载

InputStream stream = ProductVersionService.class.getResourceAsStream("/application.p‌​roperties");
properties.load(stream);

您需要指定属性文件的完整路径,从根目录到文件本身:
/main/resources/application.properties
由于您的
属性
文件将从
war
包中读取,因此最简单的解决方案是将它们作为
资源束
加载:

ResourceBundle resourceBundle = ResourceBundle.getBundle("main.resources.application");
String prop = resourceBundle.getString("nameofproperty");
System.out.println(prop);
Properties prop = new Properties();
prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("/main/resources/application.properties"));

我可以看到,您正在使用Maven构建这个项目,因此最终的jar也不会有src/main/resource或src/main/java。所有这些目录都将被删除,其下的所有内容都将添加到jar的根目录,因此使用src/main/*引用路径将导致错误。你应该利用


Thread.currentThread().getContextClassLoader().getResourceAsStream(“application.properties”)

无需开发自定义内容

如果您遵循Spring体系结构,则可以使用此类:

org.springframework.core.io.support.PropertiesLoaderUtils

假设将
资源
”内容添加到类路径中,您正在放置正确的路径。生成路径中有什么?请删除斜杠字符。另外,在我的程序中,我使用
Thread.currentThread().getContextClassLoader().getResourceAsStream
,但我不确定这是否有区别。您有任何错误吗?@cesarse否,这将使应用程序在包含
ProductVersionService
的包中查找
属性
文件。正确!但是路径应该是
/main/resources/application.properties
。修复这个问题,它将是+1。@brano88此外,根据构建阶段的不同,路径可能会有所不同。完整的答案需要说明如何验证(依赖于ide/构建过程)。
ProductVersionService.class.getResourceAsStream(“/main/resources/application.p‌​不动产)返回空值