arynaq
arynaq

Reputation: 6870

Java resources, returns nullpointer

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.

Upvotes: 3

Views: 1807

Answers (4)

ssedano
ssedano

Reputation: 8432

Bear in mind that eclipse will execute the compiled code which is in bin folder by default or target folder if you are using maven for project. This means that you must build the project.

After performing a build, take a look at the bin folder and look up the file. That is the path that you must load.

Assuming you did that and that the resource ends up in the classpath root then the standard way would be:

ClassLoader.getSystemResourceAsStream("file.txt");

But if you are still having problems then try with:

Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt");

The latter form will help you if you are executing the java class in a spawn.

Upvotes: 0

Jiri Kremser
Jiri Kremser

Reputation: 12837

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.

Upvotes: 3

Akber Choudhry
Akber Choudhry

Reputation: 1785

getClass().getResource() reads from the classpath, and not the filesystem path. So, you should use package/resource notation from the root of the classpath.

Upvotes: 0

Chris O'Brien
Chris O'Brien

Reputation: 372

Would you not use BufferedReader and read the file into a String?

Upvotes: -1

Related Questions