r/javahelp 8d 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

Show parent comments

1

u/Born-Ad4658 8d ago edited 8d ago

Its not using a framework or library

I don't think the issue is with the actual code but rather how I have my project or files set up

2

u/_Super_Straight 8d ago

So plain java cli?

Tell us more about definition of IMAGE_DIR and fnm

1

u/Born-Ad4658 2d ago

1

u/_Super_Straight 2d ago edited 2d ago

Ok. Which file has the problematic code?

Edit: NVM, found it. The problem is your directory structure. The ImageLoader class is expecting the Images/ folder to be inside src/, and since it is not, it's throwing NullPointerException. Now you have two choices:

  1. Put your Images folder inside src, or
  2. Set IMAGES_DIR = System.getProperty("user.dir")+"Images/";

If you want to bundle your Images, Sounds etc. Folders inside your jar file, you'll need to put them inside a resources folder which should be located inside your src folder. I'd suggest reading about these folder structures online for more accurate folder structure. I'm away from system so I can't check it now.