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

Java 无法从线程上下文类加载器加载资源?,java,Java,我正在尝试获取java项目中提供给我的资源的完整文件路径。代码仅使用文件名无法找到文件。我需要帮助使它工作 这是项目结构: 这是代码: package com.testing.software.apps; public class FileTest { public static void main(String[]args) { String fileName = "orders-2017.txt"; String filePath = getFi

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

这是项目结构:

这是代码

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结尾,以及我如何让它只使用文件名来查找文件吗?

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;
    }
/**
*查找具有给定名称的资源。类加载器实现
*应重写此方法以指定在何处查找资源。
*
*@param name
*资源名称
*
*@返回用于读取资源的URL对象,或
*如果找不到资源,则为null
*
*@自1.2
*/
受保护的URL findResource(字符串名称){
返回null;
}
您会出错,因为您使用了错误的路径。您应该添加目录,因为该方法不会递归地遍历资源目录。尝试使用
fileName=“text files/orders/orders-2017.txt”

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


如果您想将它们保存在src/test/java中,那么它们只能从src/test/java目录中的类中获得

进一步阅读我文章中的代码是一种很好的、独立于平台的方式来查找项目中的文件,还是有更好的方法?我尝试使用缓冲读取器,如这里的示例2所示。我使用了文件路径=“..\\src\test\\resources\\text files\\orders\\orders-2017.txt”,它工作正常,没有空指针。但是,我不确定这种方法是否更好。请告知。谢谢。您可以简单地使用path.get(“text files/orders/orders-2017.txt”)来获取path对象。我建议阅读更多关于java中Path类的内容。Maven将在默认位置查找文件,对于常规代码是src/main/resources,对于测试用例是src/test/resources。