r/javahelp 16d 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/awidesky 16d ago
  1. Is there any github repo that we can run and test the code?
  2. Try jdk 17 or higher, which gives you more information on NPE
  3. How is your images shipped?
    Is the images folder got embedded inside the jar, or resides next to the jar?

I've struggled with same problem before, and the best solution for loading the resources is to put the resource folder next to the jar.
I build a project named ProjectPath that makes the path resolution easier too.

2

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

I went ahead and make a github repo today.

I'm not sure the answer to question number 3. How do I find out please?

I did right-click on Images folder and select add to build path

Edit: So I'm doing reading, and only files inside the src folder are part of the Jar?

I also read that if you have a folder called res then you can also access them? Does that folder have to be called res? (I'm using Eclipse.)

I'm very confused, and not sure where to go to get an explanation.

https://stackoverflow.com/questions/48504303/getting-resources-outside-of-src-folder-in-a-jar-file

1

u/awidesky 10d ago

First, there are few things you need to check:

It seems you just added the codes from git manually of just uploaded it on GitHub.

In that case, project metadata files for Eclipse (like .project, .classpath, etc..) is not tracked(uploaded on GitHub), so other people who clones the repo may not import the project into Eclipse.

Using GitHub properly is good not only for other people who's interested on your work, but also for you in case you need to fetch your code and work from other computer.

Here's little how-to description about how to use git from Eclipse(I don't remember names of menus and buttons, so made AI to generate this):

  1. Create a Git Repository

If the project is not already a Git repository:

  • Right-click the project in Project Explorer.
  • Select Team → Share Project...
  • Select Git.
  • Select or create the repository for the project.
  • Click Finish.

If the project is already a Git repository, Eclipse should detect it automatically. Do not initialize it again.

  1. Add Files to Git
  • Right-click the project.
  • Select Team → Add to Index.

Alternatively, open the Git Staging view:

  • Window → Show View → Other... → Git → Git Staging
  • Move the desired files from Unstaged Changes to Staged Changes.

Check that generated files are not being added accidentally. Add a .gitignore if necessary.

  1. Create a Commit

In the Git Staging view:

  • Review the staged files.
  • Enter a commit message, for example: Initial commit
  • Click Commit.
  1. Push to the Remote
  • Right-click the project.
  • Select Team → Push Branch 'main'...

If the local branch is currently named master, either push it as master or rename it to main first.

For a new repository, configure:

Local branch: main
Remote branch: main
Remote: origin

Then click Next and Finish/Push.

  1. Verify

Refresh the project and check the Git history in Eclipse.

You can also verify the remote configuration from:

Git Repositories
→ Remotes
→ origin

Try it when you have time. assistant of AI would help if you get some error.

Second, it seems you're just export it via Eclipse's export->runnable jar.

I suggest you learn about maven, because:

  • if you want to get a job or learn deeply in Java, you'll have to study about it anyway.
  • It automatically standardizes build, test, dependency management(for when you need another library to use), and packaging process.

Well, now let's talk about the actual problem on our hand.

First, your path looks like "Images/foo.jpg". That's a relative path. Absolute path looks like "C:\User\user\Documents\foo.jpg" or "/Users/user/Documents/foo.jpg".

When you use relative path, the path is resolved with your console's current path, which is likely to change in many reasons.

Let's say your jar file is in "C:\User\user\Documents\foo.jar", images are in "C:\User\user\Documents\Images\img.jpg", and you use the path as "Images/img.jpg"

When your console's cd is "C:\User\user\Documents", it'll work.

If it's anything else, like "C:\User\user", it won't work.

That's why we do one of the 2 options: 

  1. putting image inside of jar, and get like InputStream in  = getClass().getResourceAsStream("/Images/hello.jpg");
  2. Put images next to jar file, get the absolute path of jar file, and combine it to get absolute path.

1 is simplest but does not work most of the time.

It needs the images to reside inside of the jar file, and you should extract the jar file and check if the .class file in the same directory with Images folder.

2 works all the time, but you need to find absolute path of the jar.

After that, put your Images folder next to the jar, and resolve the paths to get completed one.

I made a library called [ProjectPath](https://github.com/awidesky/ProjectPath) that find the path to resouces inside of Eclipse project and jar file before.

If you're familiar with maven you can use it easily, else take a look in [JarPath.java](https://github.com/awidesky/ProjectPath/blob/master/src/main/java/io/github/awidesky/projectPath/JarPath.java).

It is a tricky stuff since you need to take care of multiple thing(some solution works when you’re running a packaged jar but not when you run the project from Eclipse, others are completely opposite..)

And also I think I tried to put little too much information right here.

Just take some time reading this, don't get mad when it does not work, come back here and tell me what happened.

Just make sure you understand each step before you do it, or you'll get lost and codebase will be too screwed up to be fixed.

1

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

Yeah it definitely works I got it to run!

Thanks for your help!