Java:获取主应用程序而不是jar的资源路径

时间:2019-08-13 05:55:26

标签: java

这里已经讨论了很多有关获取资源的内容。  如果已经有了解决方案,请指向我,因为找不到。

我有一个使用多个jar的程序。  在其中一个jar中,我在main / resources文件夹下添加了一个属性文件。

我已将以下方法添加到jar项目中以进行读取:

public void loadAppPropertiesFile() {

    try {
        Properties prop = new Properties();
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        String resourcePath = this.getClass().getClassLoader().getResource("").getPath();
        InputStream stream = loader.getResourceAsStream(resourcePath +  "\\entities.properties");
        prop.load(stream);
        String default_ssl = prop.getProperty("default_ssl");
    }catch (Exception e){

    }
}

问题(?)是资源路径给了我target \ test-clasess的路径,但路径在调用应用程序目录下,尽管加载代码存在于jar中!

此jar内容:

enter image description here

通过maven依赖将jar添加到主项目。

如何克服这种状态并读取jar资源文件?

谢谢!

2 个答案:

答案 0 :(得分:2)

我建议使用用于加载类的类加载器,而不是上下文类加载器。

然后,您有两个选择来获取jar文件根目录中的资源:

  • 使用Class.getResourceAsStream,以绝对路径传递(领先/
  • 使用ClassLoader.getResourceAsStream,传递相对路径(仅"entities.properties"

所以其中之一:

InputStream stream = getClass().getResourceAsStream("/entities.properties");
InputStream stream = getClass().getClassLoader().getResourceAsStream("entities.properties");

我个人会使用第一个选项,因为它更简洁明了。

答案 1 :(得分:0)

您能尝试一下吗?

def render(self, screen):
    ...
    # or create a new function, it's up to you, just to this once per frame
    events = pygame.events.get()
    for e in events:
        if e.type == pygame.QUIT:
            sys.exit() # or whatever to quit the program
相关问题