【问题标题】:How define relative path to file?如何定义文件的相对路径?
【发布时间】:2020-02-12 12:33:01
【问题描述】:

我有一个使用 cucumber 和 maven 的项目,来自 Intellij IDEA。

我需要使用相对文件路径。现在我正在使用mac os,但是该项目也将在windows上使用。

  1. 如何确定 RunnerTest.java 到 mac os 的 application.properties 文件的相对路径?
  2. 为 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


【解决方案1】:

我不假装是正确的,但它确实有效:

  1. 我在src -> main 中创建了文件夹resources 并将文件夹config 移动到那里。我在src -> test 中创建了文件夹resources,并将所有其他文件夹移到那里。结果是这样的结构:
src
 |----main
 |      |
 |      |----java
 |      |----resources
 |      |        |----config
 |      |        |       |----application.properties
 |
 |----test
 |      |----resources
 |      |        |----features
 |      |        |----pipes
 |      |        |----testdata
 |      |        |----webdrivers
  1. 改为System.setProperty("TagConfigFile", "../../config/application.properties"); 我在RunnerTest.java 类中写了System.setProperty("TagConfigFile", "./config/application.properties");

如果有人提供更漂亮的工作解决方案,我会很高兴

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多