我正在尝试获取给我的 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;
}
您收到错误是因为您使用了错误的路径。您应该添加目录,因为该方法不会递归地遍历资源目录。尝试使用 fileName = "text-files/orders/orders-2017.txt";
如果您使用默认的 Maven 路径配置,并且想在 main 函数中使用此资源,则应将它们移动到 src/main/resources。
如果您想将它们保留在 src/test/java 中,那么它们只能从 src/test/java 目录中的类中使用。
关于java - 无法从线程上下文类加载器加载资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47628320/