java - Java 类加载器 getResource 中的前导斜杠 ("/") 通向何处?

标签 java

我有一个 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/

相关文章:

java - 如何强制 Checkstyle 中的枚举常量必须为大写?

java - 将 Java 对象写入文件

java - 使用 Apache POI 在 java 中编辑 Microsoft-office .doc 文件

java - BufferedReader 与 Java 中的 RandomAccessFile

java - Tomcat:调整内存比例

java - Maven 构建显示编译错误,但 Eclipse 没有

java - Z3 的 Java 插值 API 似乎返回错误的插值

java - 使用 Spring Data 从嵌入式 neo4j 迁移到 REST

java - JSplitPane 上的绘图未显示

使用 Android Studio 调试时 Java 代码执行不正确