[英]NullPointerException on getting Resource
The following code will produce a NullPointerException on uri = ...
以下代码将在
uri = ...
上产生 NullPointerException
I tried ClassLoader.getSystemResource
, getClass().getResource
or getClass().getClassLoader().getResource
我试过
ClassLoader.getSystemResource
、 getClass().getResource
或getClass().getClassLoader().getResource
Don't mater if I remove the / at the beginning or remove it at the end, it still produce a NullPointerException..如果我在开头删除 / 或在结尾删除它,请不要担心,它仍然会产生 NullPointerException ..
public class Main {
public static void main(String[] args) {
new Main();
}
private Main() {
URI uri = null;
try {
uri = ClassLoader.getSystemResource("/resources/images/flags/").toURI();
} catch (URISyntaxException e) {
e.printStackTrace();
}
if (uri != null) {
System.out.println(uri.toString());
File folder = new File(uri);
for (File file : folder.listFiles()) {
System.out.println(file.getName());
}
}
}
}
Project structure:项目结构:
Please try without "resources", because this is just the name of the folder.请尝试不使用“资源”,因为这只是文件夹的名称。 The content of this folder will be copied to the compiled classes.
此文件夹的内容将被复制到已编译的类中。
This is the answer for my comment.这是我的评论的答案。 Since
resource
is already part of the classpath, you have to change:由于
resource
已经是类路径的一部分,您必须更改:
"/resources/images/flags/"
To到
"/images/flags/"
Also, you can try relative path like "images/flags/"
此外,您可以尝试相对路径,如
"images/flags/"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.