【问题标题】:Unable to get relative path in IntelliJ for resource file - Java/Selenium无法在 IntelliJ 中获取资源文件的相对路径 - Java/Selenium
【发布时间】:2019-03-06 21:41:48
【问题描述】:

我正在努力获取资源文件夹中文件的相对路径。 我花了几个小时在其他线程中倾注并尝试其他解决方案,但都失败了,我不知道是否由于确切的语法错误,但我真的很感激一些关于确切写什么的帮助。 附上截图

文件设置

我从我的类 TestRunner 运行我的测试,该类转到 PropertiesUtil 以让浏览器在 config.properties 文件中运行测试。

config.properties 文件位于资源文件夹中,但我无法使用相对路径访问配置文件。它绝对可以正常工作,但这意味着当其他人运行它时它会失败。

如果我尝试其他路径,我会收到错误:

2019-03-06 21:21:16 INFO  TestRunner - Before running
java.io.FileNotFoundException: config.properties (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)

请帮忙!我在这方面花了太长时间。

按照建议使用 ClassLoader 进行了尝试,但这在 propertiesUtil 中不起作用,我也不太确定如何将它与我所拥有的一起编写(因为它抱怨静态/非静态)。在从 TestRunner 运行以尝试调试和理解时,它并没有给我太多有用的信息。 ClassLoader

我也尝试过在其他地方看到的类似方法。同样的问题: non-static to static error

【问题讨论】:

  • "../resources/config.properties""../../resources/config.properties" 不起作用?
  • 是的,我在发布之前尝试了这两种方法:(并得到:java.io.FileNotFoundException: ../../resources/config.properties (No such file or directory) at java.io。 java.io.FileInputStream.open(FileInputStream.java:195) 处的 FileInputStream.open0(Native Method)

标签: java intellij-idea relative-path intellij-14


【解决方案1】:

试试这样的。

   public static void readPropertiesFiles() {
        ClassLoader classLoader = PropertiesUtil.class.getClassLoader();
        String path = classLoader.getResource("config.properties").getPath();
        System.out.println(path);
    }

【讨论】:

  • 这似乎没有帮助,我无法将它放在 PropertiesUtil 文件中,当我使用调试检查它时,它没有给我任何路径或任何东西。我不是很清楚如何在输入流中使用 ClassLoader
  • 没有意识到方法是静态的,我更新了代码sn-p
【解决方案2】:

太棒了!!这非常有效。供任何发现此问题的人参考 - 这是带有上述修复的代码的屏幕截图!

Working code now implemented

【讨论】:

    猜你喜欢
    • 2013-01-06
    • 2018-03-06
    • 2020-10-31
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 2010-10-30
    • 2012-09-16
    • 1970-01-01
    相关资源
    最近更新 更多