我有一个单元测试包,其中保存了一些 txt 文件。这些是通过 getClass().getResource(file); 调用加载的,并且工作得很好。我在同一文件夹中添加了一个 csv 文件,如果我提供其名称作为参数,即 getClass().getResource("csvFile.csv");
我得到 null...有什么想法吗?
最佳答案
当您使用时
getClass().getResource("csvFile.csv");
它看起来与类相关。
当您使用时
getClass().getClassLoader().getResource("csvFile.csv");
它会查找类路径的顶级目录。
我怀疑您想要第二种形式。
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
- If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
正如您所看到的,使用了类的包名称的目录翻译。
例如,我有一个 Maven 项目,代码位于 src/main/java
下。我的资源目录src/main/resources
我将 csvFile.csv
添加到我的资源目录中,该目录将被复制到我的类路径中。
public class B {
B() {
URL resource = getClass().getClassLoader().getResource("csvFile.csv");
System.out.println("Found "+resource);
}
public static void main(String... args) {
new B();
}
}
打印内容
Found file:/C:/untitled/target/classes/csvFile.csv
这是maven从资源目录构建的区域。
关于Java - getResource 在 csv 文件上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12055905/