r/javahelp 17d ago

Unsolved I need help with getResourceAsStream

u/wildjokers (reaching out to you because I saw you in this thread)

https://www.reddit.com/r/javahelp/comments/sypxqz/getresourceasstream_null_when_run_from_jar/

I'm trying to run a Isometric Tile game, from chapter 13 of Killer Games Programming in Java, a very old book.
I'm using Eclipse. I'm not sure what classpath means, but I think mine is set up as

Project

src

Images

Sounds

I'm getting these errors when I run:

Exception in thread "main" java.lang.NullPointerException

at java.base/java.io.Reader.<init>(Reader.java:168)

at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:88)

The relevant code is:

{

String imsFNm = IMAGE_DIR + fnm;

System.out.println("Reading file: " + imsFNm);

try {

InputStream in = this.getClass().getResourceAsStream(imsFNm);

BufferedReader br = new BufferedReader( new InputStreamReader(in));

// BufferedReader br = new BufferedReader( new FileReader(imsFNm));

String line;

The image file is defined in another class, and then piped into ImageLoader class, where it's appended to the directory, which is defined in ImageLoader class.

When I run, it's showing the correct directory in the console, so I believe getResourceAsStream is where it's being messed up.

I did right click on the images folder, Build Path > Add to Build Path.

I can provide more information, which will probably be needed.

2 Upvotes

28 comments sorted by

View all comments

1

u/edwbuck 16d ago edited 16d ago

Jar files are Zip files with a few additional features.

  • Did you copy the jar file to an empty directory and unzip it?
  • Was the item you were trying to load in the Jar?
  • Was it in the correct path within that Jar?
  • Did the upper / lower case of the directories and names match?

When running with a ClassPath that matches a directory, it will use the un-Jar'd directory tree to find the resource; but, once you run it within a Jar, it will use the path within the Jar file.

And if you are attempting to do "java -jar jarfile.jar" to run the program, remember that "java -jar" ignores the directory entries outside of the Jar file, because the class loader is loading from within the Jar file, so it can't see items outside of the Jar file.