Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java resources, returns nullpointer

Tags:

java

resources

I have an image in my resources folder in eclipse that I use, the problem is I do not know how to include it, the absolute path is very long and getResource returns a nullpointer. I have searched google and SO and tried the usual solutions to no avail. The resources folder is in my buildpath, the class I am running the code from is in the buildpath but both of the following returns null.

System.out.println(getClass().getResource("data.txt"));
System.out.println(getClass().getResource("/resources/data.txt"));

Now trying :

System.out.println(getClass().getResource("001.txt"));

Still returns null.

System.out.println(getClass().getResource("/001.txt"));

Also null.

Right clicking the file and finding its path relative to the workspace (right-click file, properties, path)

System.out.println(getClass().getResource("/ovinger/resources/sokoban_levels/001.txt"));

Also null

Here is images of the workspace and the resources folder. The code is being run from "TestSokoban.java" Buildpath Workspace I was even worried that eclipse lacked the rights to search my desktop, run as admin, still same problem.

like image 492
arynaq Avatar asked Sep 08 '26 19:09

arynaq


1 Answers

There is nothing easier than to find out where the root of the relative path is, by running System.out.println(getClass().getResource("."));. And then modify the path to fit the relative path properly. It should be the package, where the class is located, btw.

like image 156
Jiri Kremser Avatar answered Sep 11 '26 07:09

Jiri Kremser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!