无法从线程上下文类加载器加载资源?

时间:2017-12-04 07:19:58

标签: java

我正在尝试获取给我的java项目中资源的完整文件路径。代码无法仅使用文件名查找文件。我需要帮助才能使它发挥作用。

这是项目结构:

enter image description here

这是代码

package com.testing.software.apps;

public class FileTest {

    public static void main(String[]args) {
        String fileName = "orders-2017.txt";
        String filePath = getFilePath(fileName);
        System.out.println("File path is: " + filePath);
    }

    public static String getFilePath(String fileName) {
        String fullFilepath = Thread.currentThread().
                getContextClassLoader().
                getResource(fileName).
                getPath();
        return fullFilepath;
    }

}

此代码在" getPath();"中引发空指针异常。线。我发现异常发生是因为这行" getResource(fileName)"返回一个空URL对象。在检查getResource代码时,我终于看到" url = findResource(name);"返回null。

public URL getResource(String name) {
    URL url;
    if (parent != null) {
        url = parent.getResource(name);
    } else {
        url = getBootstrapResource(name);
    }
    if (url == null) {
        url = findResource(name);
    }
    return url;
}

查看java.net.URL findResource的定义,我发现它总是返回null,从而一直给我一个null。

protected URL findResource(String name) {
    return null;
}

有人可以解释一下为什么这段代码总是会给出null,以及如何只使用文件名让它找到文件?

1 个答案:

答案 0 :(得分:2)

ClassLoader是一个抽象类。方法findResource在默认实现中返回null。在运行时,应该使用和实现此类来覆盖此方法。

/**
     * Finds the resource with the given name. Class loader implementations
     * should override this method to specify where to find resources.
     *
     * @param  name
     *         The resource name
     *
     * @return  A <tt>URL</tt> object for reading the resource, or
     *          <tt>null</tt> if the resource could not be found
     *
     * @since  1.2
     */
    protected URL findResource(String name) {
        return null;
    }

你错了,因为你使用了错误的路径。您应该添加目录,因为该方法不会递归通过资源目录。试试fileName = "text-files/orders/orders-2017.txt";

如果您使用默认的maven路径配置,并且如果要在main函数中使用此资源,则应将它们移动到src / main / resources。

如果你想将它们保存在src / test / java中,那么它们只能在src / test / java目录中的类中使用。

相关问题