【发布时间】:2020-02-12 12:33:01
【问题描述】:
我有一个使用 cucumber 和 maven 的项目,来自 Intellij IDEA。
我需要使用相对文件路径。现在我正在使用mac os,但是该项目也将在windows上使用。
- 如何确定 RunnerTest.java 到 mac os 的 application.properties 文件的相对路径?
- 为 Windows 定义相同的路径会有什么不同吗?
这是我的 RunnerTest.Java 类
public class RunnerTest {
public static void main(String[] args) throws Throwable {
System.setProperty("TagConfigFile", "../../config/application.properties");
//...
String sConfigFile = System.getProperty("TagConfigFile", "null");
try (InputStream streamFromResources = Props.class.getClassLoader().getResourceAsStream(sConfigFile)) {
/* work wiht streamFromResources */
} catch (IOException | NullPointerException ee) {
throw new PropsRuntimeException("Failed to access properties file", ee);
}
}
}
这是我的项目结构的图像(为清楚起见,添加了突出显示):
我尝试使用这种方式。但这并没有帮助
1. "../../config/application.properties"
2. "src/resources/config/application.properties"
3. "../../resources/config/application.properties"
【问题讨论】:
-
你的方法是错误的。您不应该将属性视为“文件”,而应将其视为“资源”。因此,您应该使用
Class.getResourceAsStream访问它,然后使用该流来构建您的Properties对象。这是独立于操作系统的,并且当您将项目打包到 jar 文件中时将起作用(您当前的方法不会)。请对Java中的资源进行一些研究。这是 Oracle 的 Accessing Resources 初学者教程。 -
如果我正确理解了文档,那么您只需要使用
System.setProperty("TagConfigFile", "/config/application.properties");但在这种情况下,我得到streamFromResources = null。请帮忙:我做错了什么? -
尝试删除初始斜线。
-
唉,它没有帮助:(
标签: java path cucumber filepath