java - 如何定义文件的相对路径?

标签 java path cucumber filepath

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

我需要使用相对文件路径。现在我在 mac os 上工作,但随后该项目也会在 windows 上使用。

  1. 如何确定 macOS 中从 RunnerTest.java 到 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);
        }
    }
}

这是我的项目结构的图像(为了清晰起见,添加了突出显示):

enter image description here

我尝试过使用这样的方式。但这并没有帮助

 1. "../../config/application.properties"
 2. "src/resources/config/application.properties"
 3. "../../resources/config/application.properties"

最佳答案

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

  1. 我在 src -> main 中创建了文件夹 resources 并将文件夹 config 移至此处。我在 src -> test 中创建了文件夹 resources 并将所有其他文件夹移至此处。结果是这样的结构:
src
 |----main
 |      |
 |      |----java
 |      |----resources
 |      |        |----config
 |      |        |       |----application.properties
 |
 |----test
 |      |----resources
 |      |        |----features
 |      |        |----pipes
 |      |        |----testdata
 |      |        |----webdrivers
  • 而是System.setProperty("TagConfigFile", "../../config/application.properties"); 我在 RunnerTest.java 类中编写了 System.setProperty("TagConfigFile", "./config/application.properties");
  • 如果有人提供更漂亮的工作解决方案,我将非常高兴

    关于java - 如何定义文件的相对路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60188436/

    相关文章:

    Python 3 升级 : uninstall/reinstall 3. 6-3.7 — 现在我无法安装 Django 2.1:错误消息:[没有名为 Django 的模块]

    bash - 无法在 rmdir 中使用带波浪号的文件夹路径

    java - cucumber testng 运行程序失败

    java - 在java中缩短类型名称

    Java,将布局设置为空

    Java算法来检查字符串中的所有字符是否唯一,不适用于Hashmap?使用 map 运算符是否有更好的解决方案?

    ruby - 带 Selenium 的 capybara ,send_key 不起作用

    java - Spring:在应用程序主要方法中运行多个 "SpringApplication.Run()"

    windows - Windows 路径中多个反斜杠的记录行为

    java - 是否有适用于 Cucumber 的 TestNG 的屏幕截图 > 报告嵌入方法?