gpt4 book ai didi

java - 如何从其他 JAR 文件加载资源

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:24:36 24 4
gpt4 key购买 nike

我无法从其他运行的 jar 加载资源。这是我的设置

resource.jar  # contains resources I want to load
`-res/hwview/file1

engine.jar # my application which need resources
`-res/hwview/file2

有趣的是,使用下面的代码我可以加载 file2(在我运行的 jar 中)但不能加载 file1

String dir = "res/hwview";
Enumeration<URL> e = getClass().getClassLoader().getResources(dir);
while(e.hasMoreElements()) {
// prints only file1 from engine.jar
// (actually it's in classes directory because I run it from my IDE)
System.out.println(e.nextElement());
}

[OUTPUT]
/path/to/my/project/SiHwViewUiModel/classes/res/hwview

所以我想也许 jar 没有被 ClassLoader 拾取,所以我打印了加载的内容

ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}

[OUTPUT]
/path/to/my/project/SiHwViewUiModel/classes/
/path/to/my/project/Resources/deploy/resources.jar
... and other not so important jars

有什么想法吗?感谢您的帮助!

最佳答案

我找到了解决方案。 getResources() 方法和类似方法的问题是不能给它们一个目录,而只能给一个特定的文件。这意味着如果我想在整个类路径中搜索特定结构,我需要在基本目录中创建标记文件。

示例: 我想进入 my/path 目录 -> 创建 marker.info(名称无关紧要)文件,然后搜索它。

resources.jar
`- my/path/
|- my/directories
`- marker.info

resources2.jar
`- my/path/
|- my/other/directories
`- marker.info

# search
Enumeration<URL> urls = getClass().getClassLoader().getResources("my/path/marker.info");

# print
print(urls);
/path/to/resources.jar!/my/path/marker.info
/path/to/resources2.jar!/my/path/marker.info

关于java - 如何从其他 JAR 文件加载资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23466872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com