java - 为什么读取文件名中包含 ':' 的测试资源会导致 NPE?

标签 java scala unit-testing url uri

我正在尝试确定如何从名称中包含特殊字符 : 的资源中读取文件。我正在遍历主代码中的目录,该目录返回我用来毫无问题地提取文件的文件列表。

在我的单元测试中,做一些简单的事情:

this.getClass().getResource("/filename:containing.character")

由于 : 的存在而返回 java.lang.NullPointerException,大概是因为它认为它是一个协议(protocol)。有什么解决办法吗?我无法重命名该文件,因为文件名编码了我希望在这种情况下测试的一些信息。

最佳答案

引用资源的特殊字符

引用 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 类( 81114 )的实现符合 IETF RFC 2396 规范文档。因此,对资源的引用应该/不得包含任何冒号 : 符号。

    当使用您的输入 filename:containing.character 进行解析时,这将导致 MalformedURLException (请参阅 URL 的 OpenJDK 实现,第 652 行)。接下来,这将导致 URLClassPath(第 1254 行)中出现 null 值,因为 MalformedURLException 的前一个实例尚未“转换”为“不成功”响应this.getClass().getResource(..) 调用。

    结论

    1. 文件名中避免使用冒号 (:) 符号
    2. 在通过 Java 中的 URL 将受影响的文件处理为“资源”之前,先重命名它们。

    关于java - 为什么读取文件名中包含 ':' 的测试资源会导致 NPE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63296712/

    相关文章:

    scala - Spark Scala TF-IDF 值排序向量

    java - 将 JUnit 类别与 Maven Failsafe 插件一起使用

    java - Spring 测试MVC : Testing controller that redirects to another controller

    c++ - 使用谷歌模拟测试 C++ 时无法推断模板参数

    Java Appengine APPSTATS 导致 java 内存不足错误

    java - 想要添加表单字段并在servlet中获取它

    scala - 缺少抽象类型成员数组的类 list

    java - Eclipse - 按语句移动

    java - 如何调整 JFrame 的大小并使用按钮显示 JPanel 和/或其控件?

    java - Play Framework 2.5 - 从 scala.html 文件反向路由到 .java 文件中的变量