Java - getResource 在 csv 文件上失败

标签 java resources filepath getresource

我有一个单元测试包,其中保存了一些 txt 文件。这些是通过 getClass().getResource(file); 调用加载的,并且工作得很好。我在同一文件夹中添加了一个 csv 文件,如果我提供其名称作为参数,即 getClass().getResource("csvFile.csv"); 我得到 null...有什么想法吗?

最佳答案

当您使用时

 getClass().getResource("csvFile.csv");

它看起来与类相关。

当您使用时

 getClass().getClassLoader().getResource("csvFile.csv");

它会查找类路径的顶级目录。

我怀疑您想要第二种形式。

来自Class.getResource(String)

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/

相关文章:

java - Android O后台联网

java - IntelliJ Idea 给出 java.lang.OutOfMemoryError : Java heap space error even after increasing heap size

java - Oracle - DB 似乎打破了 JDBC 批量插入

linux - Ubuntu Linux 的资源跟踪库?

java - 在 Java 中加载一次资源

Java 文件 URI 错误?

docker - 容器的费用是多少?

lua - Lua中的相对文件路径?

android - 如何根据数据库中的路径设置存储在文件系统中的 ImageView ?

php - 如何将绝对文件路径转换为一个 CSS 可以使用的路径?