Ryan Sangha
Ryan Sangha

Reputation: 461

getResource("path") works in Intellij but not in jar file

I have a text file I need to read, where I use this LoC that works in Intellij but not in the packaged jar file. I don't rather not use the InputStreamReader as I have made an own Reader class. I read from a file in "src/controllers/MenuController", and the WorldState1.txt is in "src/files/worldstate1.txt".

GameReader.readFile(this.getClass().getClassLoader().getResource("files/WorldState1.txt").getPath());

Is there something I'm missing or have I misunderstood getResource()?

Upvotes: 2

Views: 1651

Answers (3)

Shad
Shad

Reputation: 586

I had this same problem... The files were in my jar file, pathed as expected. The project ran fine from within the IDE (Intellij), but the Jar would fail to load some of my assets.

The problem was, my development workstation is a Windows machine, which isn't case-sensitive for directories and filenames, but the file-access mechanism Java uses to read files within the JAR is case-sensitive.

So, where I had "data/zones/dynamic/myart.png" which worked when running from the IDE, the JAR wouldn't work until I changed it to read "data/Zones/Dynamic/myart.png"... just those two capitalization errors made the resource un-findable... Folks who dev on Linux don't have that problem, since the whole system is case-sensitive, they're used to being careful about such things.

So, if your code can't find your assets when running from JAR, but the files are there, double-check the path/filename for correct-case.

Remember: It's easy to check contents of a jar, just rename it as .zip and open/extract.

Good luck!

Upvotes: 1

Ryan Sangha
Ryan Sangha

Reputation: 461

Essentially the problem was that I didn't use the correct path. What I ended up doing was

 GameReader.readFile(this.getClass().getResourceAsStream("WorldState1.txt"));

I also had to read the file using

new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)).lines().collect(Collectors.toList());

instead of a Files.readAllLines(); since it now is a stream. Hope this helps anyone else dealing with the same issue.

Upvotes: 0

Maxim
Maxim

Reputation: 99

First of all its not recomended to use getClassLoader() anymore since java 9 (or probably since newer version)

If the line of code you provided from MenuController class? If so MenuController.class.getResource or this.getClass().getResources point you to its directory: src/controllers/ and to this path you add files/WorldState1.txt. You need to build relative path by using .. or use another "startingpoint" like SomeClassInSRCFolder.class.getResource("files/WorldState1.txt)

Upvotes: -1

Related Questions