为什么读取文件名中带有“:”的测试资源会导致 NPE?
Why does reading a test resource with ':' in filename result in a NPE?
我正在尝试确定如何从名称中带有特殊字符 :
的资源中读取文件。我正在遍历我的主代码中的目录,returns 我用来毫无问题地摄取文件的文件列表。
在我的单元测试中做一些简单的事情:
this.getClass().getResource("/filename:containing.character")
returns一个java.lang.NullPointerException
由于:
的存在,大概是因为它认为它是一个协议。解决这个问题的方法是什么?我无法重命名文件,因为文件名编码了我在这种情况下要测试的一些信息。
引用资源的特殊字符
引用 T. Berners-Lee 等人的 IETF RFC 2396 规范,可从此处访问:https://www.ietf.org/rfc/rfc2396.txt
2.2. Reserved Characters
Many URI include components consisting of or delimited by, certain
special characters. These characters are called "reserved", since
their usage within the URI component is limited to their reserved
purpose. If the data for a URI component would conflict with the
reserved purpose, then the conflicting data must be escaped before
forming the URI.
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
"$" | ","
和
- URI 语法组件
The URI syntax is dependent upon the scheme. In general, absolute
URI are written as follows:
<scheme>:<scheme-specific-part>
后果
Java的 URL
class (8, 11, 14) 的实现符合 IETF RFC 2396 规范文档。因此,对资源 should/must 的引用不包含任何冒号 :
符号。
当使用您的输入 filename:containing.character
进行解析时,这将导致 MalformedURLException
(请参阅 URL 的 OpenJDK 实现,第 652 行)。接下来,这将导致 URLClassPath 中的 null
值(第 1254 行),因为 MalformedURLException
的先前实例尚未“转换”为对 this.getClass().getResource(..)
调用的“不成功”响应.
结论
- 避免在文件名中使用冒号 (
:
) 符号 OR
- 重命名受影响的文件,然后通过 Java 中的 URL 将它们作为“资源”处理。
除了@MWiesner 的回答。
如果我们已经有了这样的文件,我们能做些什么?
您可以通过参数指定包含这些文件的文件夹。然后遍历children列表,通过简单的名字比较找到想要的文件。
我正在尝试确定如何从名称中带有特殊字符 :
的资源中读取文件。我正在遍历我的主代码中的目录,returns 我用来毫无问题地摄取文件的文件列表。
在我的单元测试中做一些简单的事情:
this.getClass().getResource("/filename:containing.character")
returns一个java.lang.NullPointerException
由于:
的存在,大概是因为它认为它是一个协议。解决这个问题的方法是什么?我无法重命名文件,因为文件名编码了我在这种情况下要测试的一些信息。
引用资源的特殊字符
引用 T. Berners-Lee 等人的 IETF RFC 2396 规范,可从此处访问:https://www.ietf.org/rfc/rfc2396.txt
2.2. Reserved Characters
Many URI include components consisting of or delimited by, certain special characters. These characters are called "reserved", since
their usage within the URI component is limited to their reserved
purpose. If the data for a URI component would conflict with the
reserved purpose, then the conflicting data must be escaped before
forming the URI.reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
和
- URI 语法组件
The URI syntax is dependent upon the scheme. In general, absolute URI are written as follows:
<scheme>:<scheme-specific-part>
后果
Java的 URL
class (8, 11, 14) 的实现符合 IETF RFC 2396 规范文档。因此,对资源 should/must 的引用不包含任何冒号 :
符号。
当使用您的输入 filename:containing.character
进行解析时,这将导致 MalformedURLException
(请参阅 URL 的 OpenJDK 实现,第 652 行)。接下来,这将导致 URLClassPath 中的 null
值(第 1254 行),因为 MalformedURLException
的先前实例尚未“转换”为对 this.getClass().getResource(..)
调用的“不成功”响应.
结论
- 避免在文件名中使用冒号 (
:
) 符号 OR - 重命名受影响的文件,然后通过 Java 中的 URL 将它们作为“资源”处理。
除了@MWiesner 的回答。
如果我们已经有了这样的文件,我们能做些什么?
您可以通过参数指定包含这些文件的文件夹。然后遍历children列表,通过简单的名字比较找到想要的文件。