Class.getResource() 和 Class.getResourceAsStream() 方法是相对于类位置的。它们旨在用于此目的。
来自 javadoc
Finds a resource with a given name. The rules for searching resources associated
with a given class are implemented by the defining class loader of the class. This
method delegates to this object's class loader. If this object was loaded by the
bootstrap class loader, the method delegates to ClassLoader.getSystemResource(java.lang.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').
一个示例程序,如果存在,它将获取 src/resources/test.properties 中文件的 url。
public class TestGetResource {
public TestGetResource(){
Object resource = this.getClass().getResource("/test.properties");
System.out.println(resource);
}
public static void main(String args[]){
new TestGetResource();
}
}
调试试试这个
Object resource = this.getClass().getResource("/");
这应该返回项目的二进制路径。看看那里 NetBeans 应该在创建项目时复制那里的所有资源,如果没有,那么你将得到空值。
你的目录结构应该是
src/main/java
src/main/resources