我有一个 jar (foo.jar),它的根目录中有一个文件 - 1.txt。
我尝试运行以下命令 -
MyTestClass.class.getClassLoader().getResource("/1.txt");
jar (foo.jar) 是我在类路径中的全部。
我希望这会起作用,因为“/”应该引导我到类路径/jar 的根目录(根据我在 stackoverflow 中阅读的其他答案)。这将返回空值。
但似乎领先的“/”对我来说没有按预期工作。
我想通了,它奏效了 没有 这/-
MyTestClass.class.getClassLoader().getResource("1.txt") --> jar:file:/tmp/myjar.jar!/1.txt
在 getResouce 中引导“/”的作用/目的是什么?
最佳答案
I expected this to work as the "/" is supposed to lead me to the root of the classpath/jar (according to other answers I've read in stackoverflow).
前导斜杠仅适用于
class.getResource()
覆盖其默认行为。 class.getClassLoader().getResource()
没有前导斜线概念,所以它总是返回 null
.在这种情况下,IMO 应该抛出异常,但幸运的是,这在 Guava 的 Resources
中得到了解决。 .
关于java - Java 类加载器 getResource 中的前导斜杠 ("/") 通向何处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47900677/